Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Cushty's avatar

Spatie Media library get url

Hi, i am trying to get image URLs and audio URLs from my Spatie media collections. I learning so use GitHub Copilot Chat and it has been really good at helping (with me making sure it's correct) in order to get the URLs it says I have to map through the spatie collection. I may be wrong but I thought getting the URL for an image and audio file would be easier.

class WelcomeController extends Controller
{
    public function index(Meditation $meditation): \Inertia\Response
    {

        $meditations = Meditation::select(['id', 'title', 'description'])->with('media')->get();

        $meditations->transform(function ($meditation) {
            $imageFiles = $meditation->getMedia('images')->map(function ($media) {
                $media->url = $media->getUrl();
                return $media;
            });

            $audioFiles = $meditation->getMedia('audios')->map(function ($media) {
                $media->url = $media->getUrl();
                return $media;
            });

            $meditation = collect($meditation)->put('imageFiles', $imageFiles)->put('audioFiles', $audioFiles);

            return $meditation;
        });

        return Inertia::render('Welcome', compact('meditations',));

    }
}

Is this the right way of doing this? It works and it shows on the React frontend via Inertia but just thought there is an easier way of achieving the same thing, thanks

0 likes
1 reply
maxxxir's avatar

well you have to generate the url somewhere in the backend , i'd append a custom attribute in the model

class Meditation {
	protected $appends = ['audioFiles'];

	public function getAudioFilesAttribute()
	{
		return collect($this->getMedia('audios'))
			->transform(
				fn($item) =>  $item->getUrl()
			);
	}
}

Please or to participate in this conversation.