In this line you are comparing a query builder instance to a string:
if($user->tokens()->where('id', $bt) == $bt)
You can change it to:
if($user->tokens()->where('id', $bt)->exists())
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
My Laravel 8 application has an REST Api for other applications to login and logout with. I'm able to log a user in successfully and send back a token to put in the headers for all requests that require an auth token.
The problem I'm having right now is logging the user out. I have a method for logging out that has the following line of code.
I'm trying to use the Sanctum tokens. I do see that the personal_access_tokens table is populated. I'm just not sure why my User tokens array is empty.
$user->tokens()
I've looked at the array that comes back when calling this and it is empty. I'm not sure where my tokens are being stored or how to delete them. In theory I should be able to call $user->tokens()->delete() but like I said, there are not tokens to be found after I look up the user in the DB.
here is my current logout code.
public function logout(Request $request)
{
$user = User::where('email', $request->email)->first();
$bt = $request->bearerToken();
// return response()->json([
// 'bt' => $user->tokens()
// ]);
///I'd like to check to see if the bearerToken in header matches before deleting
///not sure if ->where('id') is the right way to find if the tokens match
if($user) {
if($user->tokens()->where('id', $bt) == $bt)
{
$user->tokens()->where('id', $bt)->delete();
}
}
else
{
return response()->json([
'status_code' => 400,
'message' => 'We could not locate the proper info in order to logout this user'
]);
}
$request->user()->currentAccessToken()->delete();
return response()->json([
'status_code' => 200,
'message' => 'Logged out successfully'
]);
}
Please or to participate in this conversation.