试图获取非对象的属性-Laravel 5 [英] Trying to get property of non-object - Laravel 5

查看:206
本文介绍了试图获取非对象的属性-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('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'];

    }

架构

users

news

控制器

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

刀片

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

当我尝试删除刀片服务器{{ $article->postedBy }}中的名称时,它会输出id,但是当我尝试在其中添加-> name时,它会显示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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆