DEV Community

Discussion on: How to Create a Secure CRUD RESTful API in Laravel 8 and 7 Using Laravel Passport

Collapse
 
benjaminv profile image
benjaminv
public function logout (Request $request) {
        $accessToken = auth()->user()->token();
        $token = $request->user()->tokens->find($accessToken);
        $token->revoke();

        return response([
            'message' => 'You have been successfully logged out.',
        ], 200);
    }
Enter fullscreen mode Exit fullscreen mode

This makes sense I however got this error, do not know why,
Call to a member function token() on null

Thread Thread
 
benjaminv profile image
benjaminv

I figured out what happened. Before you can log a user out via API, you will need to pass authentication first and then log your login off. Therefore the route logout has to be underneath the middleware auth. For convenience I grouped it with the /user route that is used in this tutorial.

Route::middleware('auth:api')->group(function (){
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
    Route::post('logout', [
        AuthController::class, 'logout'
    ]);
});
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
abhaydix07 profile image
Abhaydix07

Thankyou Sir