Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 7 Sanctum logout

I'm using Laravel 7 with Sanctum authentication for my app.
How can i implement the logout procedure?
I use:

Auth::user()->tokens()->delete();

and it works, but It delete all tokens of this user. i would like to delete only the token of the user who requested the logout, in this way the other sessions should remain open

like image 272
enfix Avatar asked Jun 21 '20 09:06

enfix


3 Answers

You need to specify the user :

// Revoke a specific user token
Auth::user()->tokens()->where('id', $id)->delete();
// Get user who requested the logout
$user = request()->user(); //or Auth::user()
// Revoke current user token
$user->tokens()->where('id', $user->currentAccessToken()->id)->delete();

Update of Laravel 7, 8 :

// Revoke the token that was used to authenticate the current request...
$request->user()->currentAccessToken()->delete();

// Revoke a specific token...
$user->tokens()->where('id', $tokenId)->delete();
like image 125
sta Avatar answered Oct 08 '22 19:10

sta


Update for Laravel 8.x.x

You can use three different approaches

// Revoke all tokens...
$user->tokens()->delete();

// Revoke the token that was used to authenticate the current request...
$request->user()->currentAccessToken()->delete();

// Revoke a specific token...
$user->tokens()->where('id', $tokenId)->delete();
like image 17
Lonare Avatar answered Oct 08 '22 17:10

Lonare


For the logout, you can directly delete the token if you use currentAccessToken().

$request->user()->currentAccessToken()->delete();
like image 8
Pj Salita Avatar answered Oct 08 '22 18:10

Pj Salita