enfix
enfix

Reputation: 6970

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

Upvotes: 26

Views: 44379

Answers (5)

user311086
user311086

Reputation: 1088

To Logout, In laravel 9 & 10

use Laravel\Sanctum\PersonalAccessToken;

// Get bearer token from the request
$accessToken = $request->bearerToken();
        
// Get access token from database
$token = PersonalAccessToken::findToken($accessToken);
    
// Revoke token
$token->delete();

Upvotes: 12

Hesam Moosapour
Hesam Moosapour

Reputation: 594

Assuming that all of your tokens are for authentication:

$user = \auth('sanctum')->user();
foreach ($user->tokens as $token) {
    $token->delete();
}

Upvotes: 0

STA
STA

Reputation: 34688

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, 9, 10 :

// 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();

Upvotes: 44

fajar wz
fajar wz

Reputation: 74

for people who got error regarding currentAccessToken() that null or undefined, don't forget to put your logout route inside auth:sanctum middleware.

so after using

$request->user()->currentAccessToken()->delete();

put the logout route like this:

Route::middleware('auth:sanctum')->group( function () {
    Route::post('logout', [AuthController::class, 'signout']);
});

Upvotes: 4

Pj Salita
Pj Salita

Reputation: 141

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

$request->user()->currentAccessToken()->delete();

Upvotes: 14

Related Questions