francoboy7's avatar

Displaying user name of a relationship

Book Model

class Book extends Model
{
    protected $primaryKey = 'book_id'; // or null

    public $incrementing = false;

    public function tracks ()
    {
        return $this->hasMany('App\Track', 'book_id', 'book_id');
    }
}

Track Model

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


        public function book ()
        {
            return $this->hasOne('App\Book', 'book_id', 'book_id');
        }
}

Books Table enter image description here

Tracks Table enter image description here

User Table https://i.imgur.com/1YDl2gA.png

Here lies my problem (one of them anyway) It doesn't display anything... I know it has something to do with array VS collection but I dont know what.

So each row in Track table belongs to a specific user

How would I go about displaying the user name which belongs to a track.

@foreach ($book->tracks as $key=>$track)

    {{ $track->country }} // this works
    
    {{ $track->user['name'] }} // this doesn't display anything
    
    {{$track->user-name }} // this throws "Trying to get property of non-object"
    
@endforeach

Thanks

0 likes
6 replies
sgtpepper's avatar

The problem might be that an specific track does not have a user related to it so $track->user would become null and then you try to access a property name so php complains because that is not an object. Luckily Laravel 5.5 introduced a Null object helper with the optional() function so you can try to access properties on the object only if it really exists in this case you could try something like this

    {{  optional($track->user)->name }}

If there is a user related Laravel will delegate the property or method call to the User Model but if there's not a user it will simply return null

There is a lesson on this feature here at Laracasts that describe it better than me https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/19

francoboy7's avatar

Table User added

{{  optional($track->user)->name }}

Is not working though....

{{  dd($track->user) }}

gives out null

sgtpepper's avatar

If $track->user returns null it means that there is not a user related to that track

francoboy7's avatar
francoboy7
OP
Best Answer
Level 7

Ok beginner mistake, I did some migrate:refresh and did not recreate users so the table was empty...

Sorry for the dumb question

Cheers

Please or to participate in this conversation.