php 试图获取非对象的属性 - Laravel 5
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32469542/
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
Trying to get property of non-object - Laravel 5
提问by wobsoriano
I'm trying to echo out the name of the user in my article and I'm getting the ErrorException: Trying to get property of non-object
. My codes:
我试图在我的文章中呼出用户的名字,我得到了ErrorException: Trying to get property of non-object
. 我的代码:
Models
楷模
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('App\User');
}
protected $table = 'news';
protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
}
2. User
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
Schema
架构
table users
桌子 users
table news
桌子 news
Controller
控制器
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
Blade
刀刃
{{ $article->postedBy->name }}
When I try to remove name in the blade {{ $article->postedBy }}
it outputs the id
, but when I try to add the ->name there it says Trying to get property of non-object
but I have a field name
in my table and a User
model. Am I missing something?
当我尝试删除刀片中的名称时,{{ $article->postedBy }}
它会输出id
,但是当我尝试在那里添加 ->name 时,它说Trying to get property of non-object
但name
我的表中有一个字段和一个User
模型。我错过了什么吗?
回答by Jimmy Zoto
Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).
您的查询是返回数组还是对象?如果你把它转储出来,你可能会发现它是一个数组,你所需要的只是一个数组访问([])而不是一个对象访问(->)。
回答by wobsoriano
I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo
. Here it is:
我通过使用 Jimmy Zoto 的答案并将第二个参数添加到我的belongsTo
. 这里是:
First, as suggested by Jimmy Zoto, my code in blade from
首先,按照 Jimmy Zoto 的建议,我在 Blade 中的代码来自
$article->poster->name
to
到
$article->poster['name']
Next is to add a second parameter in my belongsTo
,
from
接下来是在 my 中添加第二个参数belongsTo
,来自
return $this->belongsTo('App\User');
to
到
return $this->belongsTo('App\User', 'user_id');
in which user_id
is my foreign key in the news table.
其中user_id
是我在新闻表中的外键。
回答by Bruce Tong
I implemented a hasOne
relation in my parent class, defined both the foreign and local key, it returned an object but the columns of the child must be accessed as an array.
i.e. $parent->child['column']
Kind of confusing.
我hasOne
在父类中实现了一个关系,定义了外键和本地键,它返回了一个对象,但子类的列必须作为数组访问。
即$parent->child['column']
有点令人困惑。
回答by Mehmet Bütün
If you working with or loops (for
, foreach
, etc.) or relationships (one to many
, many to many
, etc.), this may mean that one of the queries is returning a null
variable or a null
relationship member.
如果您使用 或 循环(for
、foreach
等)或关系(one to many
、many to many
等),这可能意味着其中一个查询正在返回null
变量或null
关系成员。
For example: In a table, you may want to list users
with their roles
.
例如:在一个表中,您可能希望列出users
他们的roles
.
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->role->name }}</td>
</tr>
@endforeach
</table>
In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }}
with {{ !empty($user->role) ? $user->role->name:'' }}
, like this:
在上述情况下,即使有一个没有角色的用户,您也可能会收到此错误。此时应更换{{ $user->role->name }}
使用{{ !empty($user->role) ? $user->role->name:'' }}
,这样的:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
</tr>
@endforeach
</table>
回答by Nadeem Qasmi
It happen that after some time we need to run
碰巧过了一段时间我们需要运行
'php artisan passport:install --force
again to generate a key this solved my problem ,
再次生成一个密钥,这解决了我的问题,
回答by Ajay
Laravel optional() Helper is comes to solve this problem. Try this helper so that if any key have not value then it not return error
Laravel optional() Helper 就是来解决这个问题的。试试这个助手,这样如果任何键没有值,那么它就不会返回错误
foreach ($sample_arr as $key => $value) {
$sample_data[] = array(
'client_phone' =>optional($users)->phone
);
}
print_r($sample_data);
回答by Aditya Tomar
REASON WHY THIS HAPPENS (EXPLANATION)
发生这种情况的原因(解释)
suppose we have 2 tables usersand subscription.
假设我们有 2 个表users和subscription。
1 user has 1 subscription
1 个用户有 1 个订阅
IN USER MODEL, we have
在用户模型中,我们有
public function subscription()
{
return $this->hasOne('App\Subscription','user_id');
}
we can access subscription details as follows
我们可以按如下方式访问订阅详细信息
$users = User:all();
foreach($users as $user){
echo $user->subscription;
}
if any of the user does not have a subscription, which can be a case. we cannot use arrow function further after subscription like below
如果任何用户没有订阅,这可能是一种情况。订阅后我们不能进一步使用箭头功能,如下所示
$user->subscription->abc [this will not work]
$user->subscription['abc'] [this will work]
but if the user has a subscription
但如果用户有订阅
$user->subscription->abc [this will work]
NOTE: try putting a if condition like this
注意:尝试放置这样的 if 条件
if($user->subscription){
return $user->subscription->abc;
}
回答by ParisaN
I had also this problem. Add code like below in the related controller (e.g. UserController)
我也有这个问题。在相关控制器中添加如下代码(例如 UserController)
$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);