Question: I get this error when i am trying to logout the user

```
  public function logout(Request $request)
    {
       $request->user()->tokens()->delete();
    }

```

[![enter image description here](https://i.stack.imgur.com/09T6r.png)](https://i.stack.imgur.com/09T6r.png)

Answer: 
You need to include the API route inner the Sanctum Auth middleware like below:

```
Route::group(['middleware' => ['auth:sanctum']], function() {    
  Route::post('logout',   [AuthController::class, 'logout']);
});

```

`Auth::user()->token()` is only valid by passing the Sanctum middleware.  

[Check this #1](https://i.stack.imgur.com/DeGWU.png)  

[Check this #2](https://i.stack.imgur.com/nm0Hp.png)
This worked for me, Change this code in your `Controller.php` to,

```
public function logout(Request $request){
    Auth::user()->tokens()->delete();
    return [
        'message' => 'logged out'
    ];
}

```

And make sure your Route POST request is protected in `api.php`, change the code to below

```
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');

```