2
votes

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
1

1 Answers

1
votes

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 );