francoboy7
300
6
Mix

Displaying user name of a relationship

Posted 1 year ago by francoboy7

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

Please sign in or create an account to participate in this conversation.