Remove a laravel passport user token

Viewed 12167

In my unit test, I have a user for whom I generate a token:

$tokenString = $this->user->createToken('PHPunit', ['example'])->accessToken;

How can I afterward delete this user's token?

4 Answers

This is what I do when a user logged out.

public function logout() {
    Auth::user()->tokens->each(function($token, $key) {
        $token->delete();
    });

    return response()->json('Successfully logged out');
}

This code will remove each token the user generated.

I think something like this can revoke the token:

$this->user->token()->revoke()

Based on this link.

the best working solution is this

public function logout(LogoutRequest $request): \Illuminate\Http\JsonResponse
    {
        if(!$user = User::where('uuid',$request->uuid)->first())
            return $this->failResponse("User not found!", 401);

        try {
            $this->revokeTokens($user->tokens);

            return $this->successResponse([

            ], HTTP_OK, 'Successfully Logout');

        }catch (\Exception $exception) {
            ExceptionLog::exception($exception);

            return $this->failResponse($exception->getMessage());
        }

    }

    public function revokeTokens($userTokens)
    {
        foreach($userTokens as $token) {
            $token->revoke();
        }
    }

Laravel Sanctum documentation stated 3 different ways to revoke tokens. you can find it here.
but for most cases we just revoke all user's tokens via:

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

note: for some reason intelephense gives an error saying tokens() method not defined but the code works fine. Hirotaka Miyata found a workaround here.
so the over all logout method can be something like this:

public function logout()
{
    //the comment below just to ignore intelephense(1013) annoying error.
    /** @var \App\Models\User $user **/
    $user = Auth::user();
    $user->tokens()->delete();

    return [
        'message' => 'logged out'
    ];
}
Related