繁体   English   中英

致电 Laravel Sanctum 上 null 上的成员 function tokens()

[英]Call to a member function tokens() on null on Laravel Sanctum

当我尝试注销用户时出现此错误

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

在此处输入图像描述

这对我有用,将Controller.php中的代码更改为,

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

并确保您的 Route POST 请求在api.php中受到保护,将代码更改为以下

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

使用token()而不是tokens()

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

或者您可以按如下方式使用它。

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

通过使用撤销

$user = $request->user();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM