Laravel Prevent Browser Back Button After Logout

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:

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

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

Add Middleware in Route

Now open routes/web.php files and add “prevent-back-history” middleware in route file as below:

routes/web.php

In this tutorial we have learn about the Laravel Prevent Browser Back Button After Logout and its application with practical example. I hope you will like this tutorial.