首页 > 解决方案 > 为什么当用户新注册和已经登录时,注销(护照)的行为会有所不同?

问题描述

在用户新注册并被重定向到主页时 - 他们可以通过该logout()方法毫无问题地注销。

但是,当用户使用现有凭据登录然后尝试注销时 - 我收到一条错误消息,message: "Call to a member function token() on null"即使令牌不是null.

我不确定自己做错了什么,我尝试四处寻找可能的解决方案,但无济于事。

public function login(Request $request) {
    $credentials = ['email' => $request->email, 'password' => $request->password];

    if (Auth::guard('web')->attempt($credentials, false)) {
        $success = auth('web')->user()->createToken('MyApp')->accessToken;
        return response()->json([
            'message' => 'Successfully logged out',
            'loginToken' => $success
        ]);
    }

    return $this->sendError('Unauthorized.', ['error' => 'Unauthorized']);
}

public function logout(Request $request) {
    // Successfully revokes token when the user logs out if newly registered
    // However, it doesn't revoke token (logout) if the user's logged in and tries to logout

    $request->user()->token()->revoke();
    return response()->json([
        'message' => 'Successfully logged out'
    ]);
}

标签: phplaraveldebugging

解决方案


推荐阅读