IT would be nice if we could see your users table? also
Jan 27, 2018
6
Level 7
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

Tracks Table

User Table

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