php – 试图获得非对象的属性 – Laravel 5

前端之家收集整理的这篇文章主要介绍了php – 试图获得非对象的属性 – Laravel 5前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在我的文章中回显用户的名字,我得到ErrorException:尝试获取非对象的属性.我的代码

楷模

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'];

    }

架构

用户

enter image description here

表新闻

enter image description here

调节器

public function showArticle($slug)
    {
        $article = News::where('slug',$slug)->firstOrFail();
        return view('article',compact('article'));
    }

{{ $article->postedBy->name }}

当我尝试删除刀片中的名称{{$article-> postedBy}}时,它会输出ID,但是当我尝试添加 – >名称时,它会说要尝试获取非对象的属性但我有一个我的表中的字段名称用户模型.我错过了什么吗?

解决方法

您的查询是返回数组还是对象?如果将其转储出来,您可能会发现它是一个数组,您只需要一个数组访问([])而不是对象访问( – >).

猜你在找的Laravel相关文章