'How to prevent browser back button after successful login in Laravel?

I am having a problem applying custom middleware for not accessing the login route after successful login. Whenever I logged in a user if the user press the browser back button he was able to see the login page again. To prevent this I have created a middleware and disabled the cache inside its handle method but it was not working because I have multiple roles. Here is my middleware code:- My middleware name is RevalidateBackHistory and I have register it in the kernal.php file with revalidate name like this:-

'revalidate' => \App\Http\Middleware\RevalidateBackHistory::class,

in the protected $routeMiddleware group.

public function handle(Request $request, Closure $next)
{
    $response = $next($request);
    return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
        ->header('Pragma','no-cache')
        ->header('Expires','Fri, 01 Jan 1990 00:00:00 GMT');
}

Here is my web.php file:-

Route::group(['middleware' => ['guest', 'revalidate'], 'prefix' => '/'], function(){
....my guest route here
}

Route::group(['middleware' => ['auth', 'revalidate']], function() {
....my auth routes here
    Route::group(['middleware' => ['role:admin', 'revalidate'], 'namespace' => 'Backend'], function () {
    ...my admin role routes here
    }

    Route::group(['middleware' => ['role:user', 'revalidate'], 'namespace' => 'Backend'], function () {
    ...my user role routes here
    }
}

The above code is working fine for the single role but not with multiple roles because my login function is common for both the users (admin and user). What can I add in to my code to prevent the browser back button not to worked after login and vice versa for after logout.

Please help me out!



Solution 1:[1]

Hi I would do the following.

I would create a redirect on the login page if I was authorized or only show login page when not authorized. Basically the opposit of when you want to go to an unauthorized page.

again ignore the groups and only if a user is authenticated

in laraval if you have auth()->user() the user has already been validated so no need to login again. and redirect to your backend

Solution 2:[2]

I would like to do the following.

If I had authorization, I would create a redirect on the login page or only show the login page when not authorized. What you want to avoid when you want to go to an unauthorized website.

Again, ignore the groups and only if the user is authenticated

If you have auth()->user() in Laraval, the user has already been validated so you don't need to log in again. Redirect to your backend.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcel Santing
Solution 2 Hakimuddin Saifee