Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dngbit's avatar

Regenerate, invalidate session in auth guard

https://stackoverflow.com/questions/68760662/laravel-session-regenerate-and-invalidate-functions

Did someon have solution for that ? Issue is with this 2 functions. In my guard 'admin' when i log out from my guard

Auth::guard('admin')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();

I'm also log out from default 'web', 'auth' guard. So question how to run invalidate and regenerateToken for multiple guards ?

0 likes
2 replies
LaryAI's avatar
Level 58

To invalidate and regenerate the session token for multiple guards in Laravel, you can use the following approach:

  1. Create a new middleware that will handle the session invalidation and token regeneration for multiple guards. Let's name it InvalidateAndRegenerateSessionMiddleware.
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class InvalidateAndRegenerateSessionMiddleware
{
    public function handle($request, Closure $next, ...$guards)
    {
        foreach ($guards as $guard) {
            Auth::guard($guard)->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
        }

        return $next($request);
    }
}
  1. Register the middleware in the app/Http/Kernel.php file. Add the following line to the $routeMiddleware array:
protected $routeMiddleware = [
    // ...
    'invalidate' => \App\Http\Middleware\InvalidateAndRegenerateSessionMiddleware::class,
];
  1. Now, you can use the invalidate middleware in your routes or route groups to invalidate and regenerate the session token for multiple guards. For example:
Route::group(['middleware' => 'invalidate:admin,web'], function () {
    // Routes that require session invalidation and token regeneration for 'admin' and 'web' guards
});

In the above example, the invalidate middleware is applied to a route group, and it accepts a comma-separated list of guard names as parameters. You can modify the guard names according to your application's requirements.

By using this middleware, you can easily invalidate and regenerate the session token for multiple guards in Laravel.

Snapey's avatar

sorry, never felt the need for multiple guards. A user is a user. It is authorization that determines what they can do, not how they logged in.

Please or to participate in this conversation.