Posted by Arjun on Tuesday 16th February 2016

Laravel 5 - Prevent Browser back button after Logout

How to Laravel 5 Laravel 5.1 Laravel 5.x Prevent Browser back button

In this post, I would like to share a simple Laravel5 Middleware which prevents going back to the previous protected page after Logout by hitting the back button on your Browser.

When you hit the browser back button after logout, it will take you to the original page instead of redirecting to login page. It should redirect to the login page, isn't it? Here I am gonna share a Middleware which will fix this issue.

Prevent Browser back button after Logout
Let's start -

Create middleware

Create a middleware by issuing artisan command from your terminal -

php artisan make:middleware ValidateBackHistory

Laravel Prevent Browser back button

Above command will generate a middleware class called ValidateBackHistory in app/http/middleware. Open that file and add response header configurations as shown below.

namespace App\Http\Middleware;
use Closure;
class ValidateBackHistory
 * 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') //HTTP 1.0
 ->header('Expires','Sat, 01 Jan 1990 00:00:00 GMT'); // // Date in the past


Now open \app\Http\Kernel.php file, add our custom ValidateBackHistory middleware in route middleware's array.

protected $routeMiddleware = [
          'auth' => 'App\Http\Middleware\Authenticate',
          'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
          'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
          'validateBackHistory' => 'App\Http\Middleware\ValidateBackHistory',

To use this middleware you just need to call validateBackHistory middleware for routes which require user authentication.