[英]Why am I getting "Trying to get property 'username' of non-object" when trying to access "$comment->users->username"?
I'm trying to get the usernames of the users who have posted comments, however, I keep getting "Trying to get property 'username' of non-object" error.我正在尝试获取发表评论的用户的用户名,但是,我不断收到“试图获取非对象的属性‘用户名’”错误。 I believe my relationships are done correctly but I might be wrong.
我相信我的人际关系是正确的,但我可能是错的。
My tables:我的表:
Table: Users
Columns: id, username, password
Table: Comments
Columns: id, user_id, image_id, comment
Comment model:评论型号:
class Comment extends Model
{
public function users(){
return $this->belongsTo('App\User');
}
}
User model:用户模型:
class User extends Model implements Authenticatable
{
public function comments(){
return $this->hasMany('App\Comment');
}
}
I'm getting the comments like this:我收到这样的评论:
$comments = Comment::with('users')->where('image_id', $id)->get();
And then trying to loop through them in the view like this:然后尝试在视图中循环它们,如下所示:
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ $comment->users->username }}</p>
@endforeach
And when I dd($comments), I see:当我 dd($comments) 时,我看到:
#relations: array:1 [▼
"users" => null
]
I'm not sure why is it null though.我不确定为什么它是空的。
Try this尝试这个
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ !empty($comment->users->username) ? $comment->users->username : '' }}</p>
@endforeach
Also I suggest you change you relations name users
to user
另外我建议您将关系名称
users
更改为user
class Comment extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
Get comments获取评论
$comments = Comment::with('user')->where('image_id', $id)->get();
And in view并且鉴于
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
@if(!empty($comment->user))
<p>{{ $comment->user->username }}</p>
@endif
@endforeach
try this way :试试这种方式:
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ $comment->users["username"] }}</p>
@endforeach
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ optional($comment->users)->username}}</p>
@endforeach
Try this approach.试试这个方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.