Laravel 7 Sanctum 注销

Laravel 7 Sanctum logout

我正在为我的应用程序使用 Laravel 7 和 Sanctum 身份验证。
如何实现注销程序?
我使用:

Auth::user()->tokens()->delete();

它有效,但它删除了该用户的所有令牌。 我只想删除请求注销的用户的令牌,这样其他会话应该保持打开状态

您需要指定用户:

// Revoke a specific user token
Auth::user()->tokens()->where('id', $id)->delete();
// Get user who requested the logout
$user = request()->user(); //or Auth::user()
// Revoke current user token
$user->tokens()->where('id', $user->currentAccessToken()->id)->delete();

Laravel 7, 8更新:

// Revoke the token that was used to authenticate the current request...
$request->user()->currentAccessToken()->delete();

// Revoke a specific token...
$user->tokens()->where('id', $tokenId)->delete();

对于注销,使用currentAccessToken()可以直接删除token。

$request->user()->currentAccessToken()->delete();

更新 Laravel 8.x.x

您可以使用三种不同的方法

// Revoke all tokens...
$user->tokens()->delete();

// Revoke the token that was used to authenticate the current request...
$request->user()->currentAccessToken()->delete();

// Revoke a specific token...
$user->tokens()->where('id', $tokenId)->delete();