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)
use `token()` instead of `tokens()`

```
$request->user()->token()->delete();

```

Or you can use it as below.

```
Auth::user()->tokens->each(function($token, $key) {
    $token->delete();
});

```

by using revoke

```
$user = $request->user();

foreach ($user->tokens as $token) {
    $token->revoke();
}

```