Laravel 5.5试图获取非对象的属性“ id”

mor*_*ore 3 php mysql laravel laravel-5

我是Laravel的新手,我使用的是Laravel 5.5版

如果我尝试用邮递员登录。我收到“尝试获取非对象的属性'id'”错误。错误行是

    private $client;

public function __construct(){
    $this->client = Client::find(1);
}

public function login(Request $request){

    $this->validate($request, [
        'username' => 'required',
        'password' => 'required'
    ]);

    return $this->issueToken($request, 'password'); // this line has error

}
Run Code Online (Sandbox Code Playgroud)

issueToken函数

public function issueToken(Request $request, $grantType, $scope = ""){

    $params = [
        'grant_type' => $grantType,
        'client_id' => $this->client->id,
        'client_secret' => $this->client->secret,           
        'scope' => $scope
    ];

    if($grantType !== 'social'){
        $params['username'] = $request->username ?: $request->email;
    }

    $request->request->add($params);

    $proxy = Request::create('oauth/token', 'POST');

    return Route::dispatch($proxy);

}
Run Code Online (Sandbox Code Playgroud)

我在注册时遇到了相同的错误。但是我的用户成功注册了500错误(试图获取非对象的属性“ id”)

Sap*_*aik 5

错误是因为找不到记录$this->client时为null find()。您需要确定记录是否存在。

更改:

$this->client = Client::find(1);
Run Code Online (Sandbox Code Playgroud)

至:

$this->client = Client::findOrFail(1);
Run Code Online (Sandbox Code Playgroud)

docs中404如果未找到具有指定ID的记录,则将引发错误。