Ad

Why Is The Request User Null In My Logout Function?

- 1 answer

I am implementing an Authentication api in Laravel using passport.

I have implemented the login api, but there is a problem with logout api. My login code is working successfully:

public function login(Request $request){
    $request->validate([
        'email'=> 'required|string|email',
        'password'=> 'required|string',
        'remember_me'=> 'boolean',
    ]);

    $credentials= request(['email','password']);

    if(!Auth::attempt(['email' => $request->email, 'password' => $request->password])){

        return response()->json([
            'message'=> 'Unauthorized'
        ],401);

    }
    Auth::attempt(['email' => $request->email, 'password' => $request->password]);
    $user=$request->user();

    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;

    if($request->remember_me)
        $token->expires_at= Carbon::now()->addWeek(1);

    $token->save();

    return response()->json([
        'access_token'=>$tokenResult->accessToken,
        'token_type'=>'Bearer',
        'expires_at'=>Carbon::parse($tokenResult->token->expires_at)
                        ->toDateTimeString()
    ]);
}

This works successfully, however, when I use the same bearer token to revoke the token of the user I am receiving the following exception:

Call to a member function token() on null

This is referring to the first line of the logout method below.

public function logout(Request $request){
    $request->user()->token()->revoke();
    return response()->json([
        'message'=> 'Successfully logged out'
        ]);
}

Why is the output of $request->user() null?

Ad

Answer

Create a token for the authenticated user, not the guest user who made the request

$user= auth()->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->accessToken;

And when revoking

public function logout(Request $request)
{
  auth()->user()->token()->revoke();
  return response()->json([
      'message'=> 'Successfully logged out'
  ]);
}

Hope this helps

Ad
source: stackoverflow.com
Ad