In this tutorial you will learn about the Laravel Prevent Browser Back Button After Logout and its application with practical example.
Laravel Prevent Browser Back Button After Logout
In this example, we will learn to prevent browser back button after user logout, so that he will not be able to access auth protected routes or pages after logout.
In Laravel, it is quite a common problem that when user logout and then click on the back button in browser the browser shows the last loaded page from the website. In this article, I’ll show you how to prevent back button after logout in Laravel application. In Laravel, when a user logout from application and then hit the browser back button then he will be sent back to the page he was visiting before logout. Ideally, user should not be allowed to access auth middleware protected routes or pages. User should be redirect back to application login page instead of the page he was visiting.
In this tutorial, we will prevent this issue by using laravel middleware. We will create a middleware and use it with routes to prevent back button history.
Create New Middleware
In this step, we will create a new middleware using following command:
1 |
php artisan make:middleware PreventBackHistory |
Middleware Configuration
Open up PreventBackHistory.php file in app/Http/Middleware folder and replace codes with the following codes below:
app/Http/Middleware/PreventBackHistory.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Middleware; use Closure; class PreventBackHistory { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($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','Sat, 26 Jul 1997 05:00:00 GMT'); } } |
Register Middleware
In this step we have to register middleware, open Kernel.php in app/Http folder and add a new middleware in $routeMiddleware variable array as below:
app/Http/Kernel.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { ..... ..... /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ ..... 'prevent-back-history' => \App\Http\Middleware\PreventBackHistory::class, ]; } |
Add Middleware in Route
Now open routes/web.php files and add “prevent-back-history” middleware in route file as below:
routes/web.php
1 2 3 4 |
Route::group(['middleware' => 'prevent-back-history'],function(){ Auth::routes(); Route::get('/home', 'HomeController@index'); }); |