gpt4 book ai didi

laravel - 在 null 上调用成员函数 createToken()

转载 作者:行者123 更新时间:2023-12-05 05:01:36 25 4
gpt4 key购买 nike

我是 laravel api 和 laravel passport 的新手,我知道这是一个老问题,但没有答案帮助我。我正在使用 laravel passport for api注册,登录正常,但注销和错误

这是我的注册码

 public function register (Request $request) {
$validator = Validator::make($request->all(), [
'UserName' => 'required|string|max:255',
'UserFullName' => 'string|max:255',
'UserEmail' => 'required|string|email|max:255|unique:users',
'UserPhone' => 'required|string|max:255|unique:users',
'Password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails())
{
return response(['errors'=>$validator->errors()->all()], 422);
}
if ($request['UserPhone']==Null) { // will check for empty string, null values, see php.net about it
$request['UserPhone'] = NULL;
}
$request['Password']=Hash::make($request['Password']);
$request['remember_token'] = Str::random(10);
$request['UserType'] = $request['UserType'] ? $request['UserType'] : 1;
//return response($request, 200);
$user = User::create($request->toArray());
$token = $user->createToken('Laravel Password Grant Client')->accessToken;
//return response($token, 200);
$response['data']= $user;
$response['data']['token'] = $token;
return response($response, 200);
}

我的登录码

    public function login (Request $request) {
$validator = Validator::make($request->all(), [
'UserEmail' => 'required|string|email|max:255',
'Password' => 'required|string|min:6',
]);
if ($validator->fails())
{
return response(['errors'=>$validator->errors()->all()], 422);
}
$user = User::where('UserEmail', $request->UserEmail)->first();
if ($user) {
if (Hash::check($request->Password, $user->Password)) {
$token = $user->createToken('Laravel Password Grant Client')->accessToken;
$response['data']= $user;
$response['data']['token'] = $token;
return response($response, 200);
} else {
$response = ["message" => "Password mismatch"];
return response($response, 422);
}
} else {
$response = ["message" =>'User does not exist'];
return response($response, 422);
}
}

我的登出密码

public function logout (Request $request) {
//return $request->Authorization;
$token = $request->user()->token();
//return $token;
$token->revoke();
$response = ['message' => 'You have been successfully logged out!'];
return response($response, 200);
}

postman 响应

"message": "Call to a member function createToken() on null",
"exception": "Error",

最佳答案

问题出在授权上,似乎所有带有授权 header 的帖子 api 都应该通过身份验证检查,我将我的注销路由移到中间件中

Route::group(['middleware'=>['auth:api']],function(){
Route::get('/companies', 'CompanyController@index')->name('companies');
});

但我不确定为什么它不适用于 if(Auth:check){...进一步撤销代码...

关于laravel - 在 null 上调用成员函数 createToken(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62650053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com