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
Make sure you use HasApiTokens in User.php
Make sure
auth()->user()
return the Model that hasHasApiTokens
trait. If you are using multiple guards, then ensureHasApiTokens
trait is included in all the models defined inguards
andproviders
section ofconfig/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: