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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49900523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:39:20  来源:igfitidea点击:

Call to a member function createToken() on null?

laravelrestful-authentication

提问by reza baghiee

When I used the passport package , I encountered this error

我用passport包的时候遇到这个错误

Call to a member function createToken() on null

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

Why do I get this error?

为什么会出现此错误?

This is my code :

这是我的代码:

$users = Users::where('Email' , $username)
              ->where( 'Password' , $password)
              ->where('UserStatus' , config('global.active'))
              ->first();

if($users) {
    $success['token'] =  $users->createToken('MyApp')->accessToken;
    return response()->json(['success' => $success], $this->successStatus);
} else {
    return response()->json(['error'=>'Unauthorised'], 401);
}

回答by Luis felipe De jesus Munoz

$user = Auth::user();is unnecessary and is what is causing your error.

$user = Auth::user();是不必要的,并且是导致您错误的原因。

$user = Users::where('Email' , $username)->where( 'Password' , $password)->where('UserStatus' , config('global.active'))->first();
if($user){
    $success['token'] =  $user->createToken('MyApp')->accessToken;
    return response()->json(['success' => $success], $this->successStatus);
}else{
    return response()->json(['error'=>'Unauthorised'], 401);
}

回答by kmuenkel

If $userswere null, there's no way that part of the control structure where createTokenis getting called would be reached. I wonder if this is a red herring, and there's some middleware at work here. There are actually three instances of a method by that same name, and the namespace in your error message is notable absent there:

如果$users为空,则createToken无法到达被调用的控制结构部分。我想知道这是否是一个红鲱鱼,这里有一些中间件在起作用。实际上有三个同名方法的实例,并且您的错误消息中的命名空间明显不存在:

  • /vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php
  • /vendor/laravel/passport/src/ApiTokenCookieFactory.php
  • /vendor/laravel/passport/src/HasApiTokens.php
  • /vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php
  • /vendor/laravel/passport/src/ApiTokenCookieFactory.php
  • /vendor/laravel/passport/src/HasApiTokens.php

That last one is a trait being used by the User model, and is the one you're calling. But I'm wondering if that error is actually coming from one of the other two. Check your error-log, probably in /storage/logs/laravel.log, and see if there's a stack-trace that might lend a clue.

最后一个是 User 模型正在使用的特征,也是您正在调用的特征。但我想知道该错误是否真的来自其他两个错误之一。检查您的错误日志,可能在 中/storage/logs/laravel.log,看看是否有可能提供线索的堆栈跟踪。