Hamid Hosseini
Hamid Hosseini

Reputation: 433

How to retrieve the media of a related model with Laravel Medialibrary?

I have an Album model and Track model. They have OneToMany relationship. An Album can have many tracks and a track can only belong to one Album. I'm using media library to associate the files of a song which is the cover and the mp3 to a Track model.

In my AlbumController, I have a query like this;

$album = $album->where('id', $id)->with('tracks', 'artist')->first();
return view('admins.albums.show', compact('album'));

This loads the tracks of the album but not the media. In my views, I can get the media by looping through the tracks and calling the getMedia() function but what about for Api?

How can I return the media as a Json before it is sent as a response?

Upvotes: 1

Views: 2722

Answers (1)

You can use an ancestor (https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators) to append the url to the model, for example (im using a diferent model btw):

place this first in the beginning of the model (it doesnt matter):

protected $appends = [
    'logo_url'
];

and them:

public function getLogoUrlAttribute()
{
    return (empty($this->getMedia('restaurants')[0])) ? "" : $this->getMedia('restaurants')[0]->getFullUrl();
}

this code goes on the model that has the media trait attached to it.

Upvotes: 2

Related Questions