php Laravel 5.5 试图获取非对象的属性“id”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48422199/
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
Laravel 5.5 Trying to get property 'id' of non-object
提问by more
I'm new on Laravel.I used Laravel version 5.5
我是 Laravel 的新手。我使用的是 Laravel 5.5 版
If I try to login with postman.I got "Trying to get property 'id' of non-object" error.And error line is
如果我尝试使用邮递员登录。我收到“试图获取非对象的属性‘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
}
issueToken Function
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);
}
I got same error on Register.But my user successfully registered with 500 error (Trying to get property 'id' of non-object)
我在注册时遇到了同样的错误。但是我的用户成功注册了 500 错误(试图获取非对象的属性“id”)
回答by Sapnesh Naik
The error is because $this->client
is null when find()
cannot find the record.
错误是因为找不到记录$this->client
时为空find()
。
You need to be sure if the record exists or not.
您需要确定该记录是否存在。
Change:
改变:
$this->client = Client::find(1);
To:
到:
$this->client = Client::findOrFail(1);
Documentation:
文档:
From Laravel Eloquent docs,
this will throw a 404
error if no record with the specified id is found.
从Laravel Eloquent docs,404
如果没有找到具有指定 id 的记录,这将引发错误。
回答by Nimfus
Make sure you have record in database table for User model with id = 1. When you're using User::find(1) Laravel tries to get this record from database, if record is absent this will return null
确保您在数据库表中有 id = 1 的用户模型的记录。当您使用 User::find(1) 时,Laravel 尝试从数据库中获取此记录,如果记录不存在,则返回 null
回答by Sohel0415
In your issueToken()
method-
在你的issueToken()
方法中——
$client = Client::find(1);
if($client!=null){
$params = [
'grant_type' => $grantType,
'client_id' => $client->id,
'client_secret' => $client->secret,
'scope' => $scope
];
}else{
$params = [
'grant_type' => $grantType,
'client_id' => null,
'client_secret' => null,
'scope' => $scope
];
}
回答by latifa saee
I had the same problem when I was trying access an id which doesn't exist in my project database. This $user= user::findOrFail($id);
solved my problem.
当我尝试访问我的项目数据库中不存在的 ID 时,我遇到了同样的问题。这$user= user::findOrFail($id);
解决了我的问题。