skip to Main Content

I tried the logout operation by deleting all the authenticated tokens as shown in the function below:

 public function logout()
{
    auth()->user()->tokens()->delete();
    return response()->json([
        'message' => 'Logout Successful'
    ], 200);
}

The code works fine when i checked the route in Postman, but the error is shown in the controller saying:

Undefined method 'tokens'.

How do i solve this error?

The screenshot is shown below:
Controller Screenshot

2

Answers


  1. Make sure you use HasApiTokens in User.php

    // 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();
    
    Login or Signup to reply.
  2. Make sure auth()->user() return the Model that has HasApiTokens trait. If you are using multiple guards, then ensure HasApiTokens trait is included in all the models defined in guards and providers section of config/auth.php file.

    If the error is shown in IDE only, then you need to annotate the code to instruct the IDE where to look for the codes.

    Eg:

    /**
     * @var $user AppModelsUser
     */
    $user = auth()->user();
    $user->tokens()->delete();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search