试图获取非对象的属性 - Laravel 5 [英] Trying to get property of non-object - Laravel 5
问题描述
我试图在我的文章中回显用户的姓名,但我收到了 ErrorException: Trying to get property of non-object
.我的代码:
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:
模型
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('AppUser');
}
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'];
}
架构
表 users
table news
控制器
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
刀片
{{ $article->postedBy->name }}
当我尝试删除刀片 {{ $article->postedBy }}
中的名称时,它会输出 id
,但是当我尝试添加 ->在那里命名它说 Trying to get property of non-object
但我的表中有一个字段 name
和一个 User
模型.我错过了什么吗?
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?
推荐答案
您的查询返回的是数组还是对象?如果你把它转储出来,你可能会发现它是一个数组,你所需要的只是一个数组访问([])而不是一个对象访问(->).
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 (->).
这篇关于试图获取非对象的属性 - Laravel 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!