Hello Developers,
It is a common thing that after logout you should not go back to the previous page. But in your development journey, you can go back after logout. To prevent this, we can make a middleware and use it in our route group. Follow the steps to prevent the browser back button after logout in the Laravel project.
First Step: Create New Middleware
First, we will create a middleware using the below command:
php artisan make:middleware PreventBackHistory
Second Step: Middleware Configuration
Secondly, we have to configure the newly created middleware.
app/Http/Middleware/ PreventBackHistory
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class PreventBackHistory
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
return $response->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','Sat, 26 Jul 1997 05:00:00 GMT');
}
}
Third Step: Register the middleware
Thirdly, register the middleware in the Kernel.php
file.
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
....
....
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'prevent-back-history' => \App\Http\Middleware\PreventBackHistory::class
];
}
Fourth Step: User middleware in the route
Finally, add the middleware in the route.
route/web.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SampleController;
Route::group(['middleware' => 'prevent-back-history'], function () {
Route::resource('samples', SampleController::class);
}
You can add this middleware when you need this. Hope this might help you in your development journey.
Read More: Remove Public Path From URL in Laravel Without htaccess