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

panthro's avatar

Cannot logout of Sanctum (SPA)

If using the middleware 'auth:sanctum' I cannot log out of Sanctum using the advised Auth::logout() in the official documentation.

Other issues similar to this suggest doing Auth::guard('web')->logout(), but if you have a test:

 Sanctum::actingAs(User::first(), ['*'], 'web');

        $response = $this->postJson(
            route('logout')
        );

        dd(auth()->user()->username);

The user still exists in the dump.

The only solution that works is to remove the middleware, but I only want users to hit the logout route if authorized.

Please note, no tokens as it is SPA Sanctum with session/cookies.

0 likes
8 replies
cariboufute's avatar

For some reason, the only way I have been able to log out is to to put the Auth::logout() method directly into a closure in the api.php route file.

Route::post('logout', fn() => Auth::logout());
1 like
cariboufute's avatar

@panthro Not in my program. This route does not have any middleware around.

For the matter, I retested with adding auth:sanctum around the route and calling a controller method for logout. The user was still logged in.

This is why I put the route action in a closure in the first place.

2 likes
cariboufute's avatar

@panthro I have now been able to logout inside a controller method by resetting the session, but still without the auth:sanctum middleware.

Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
mabdullahsari's avatar

There is no such thing as logging out when using the sanctum guard to authenticate your routes.

"Logging out" implies terminating an existing session on the server, which in turn implies persistent state, which in turn also implies the usage of a Stateful Guard such as the web guard.

In other words, if you want to give your users the ability to log out from your application, place those routes behind the web guard, not sanctum.

Sanctum is a convenience layer to authenticate certain "Internal API routes" using the standard session mechanism. Both guards are not mutually exclusive.

panthro's avatar

@mabdullahsari but SPA Sanctum implementation does implement states via the sanctum guard, so why does the Logout method not work?

mabdullahsari's avatar

@panthro Because it delegates that work to the StatefulGuard.

If you want to log out in your routes, use that guard.

Please or to participate in this conversation.