Ad
Why Is The Request User Null In My Logout Function?
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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad