2

I'm trying to return the user name who submitted an article, but unable to access this via an eloquent relationship.

Models/Thing

public function users()
{
    return $this->belongsTo(User::class);
}

with user_id stored in the things table

However this dump isn't returning user data: dd($this->thing->users->name);

Error:

Attempt to read property "name" on null
Mike Thrussell
  • 4,175
  • 8
  • 43
  • 59

1 Answers1

1

try this

return $this->belongsTo(User::class, 'user_id', 'id');

in my view you are using users with belongTo. it will work if you will use.

public function user(){
    return $this->belongsTo( User::class );

}

and then

dd( $this->thing->user->name );
rameezmeans
  • 830
  • 1
  • 10
  • 21