php 'name' - Trying to get property of non-object-Laravel 5

'client' 'id' (5)

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,
        use Authenticatable, Authorizable, CanResetPassword;

        protected $table = 'users';

        protected $fillable = ['name', 'email', 'password'];

        protected $hidden = ['password', 'remember_token'];



table users

table news


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


{{ $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?


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.

I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:

First, as suggested by Jimmy Zoto, my code in blade from $article->poster->name to $article->poster['name']. Next is to add a second parameter in my belongsTo, from 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.

Thanks for all your help!

It happen that after some time we need to run

 'php artisan passport:install --force 

again to generate a key this solved my problem ,

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 (->).

Surprisingly or not, ->default(NULL) removes default value from a table:

public function up()
    Schema::table('client', function (Blueprint $table) {

Just omitting default call doesn't work, since laravel makes a diff between current state and current state + specified changes. No changes specified, no diff.

After that, doctrine generates ALTER TABLE statement (particularly, resulting column declaration), treating NULL value as default value not being specified.

php laravel