0

I am trying to get media for certain modal as follows:

public function show(Gallery  $gallery)
    {
       $images = $gallery->getMedia('default'); //returns images
       // $images = $gallery->getMedia('default', ['name', 'original_url']); //returns empty 
       return response()->json(['data' => $images]);
    }

when not adding filters I get the correct data as follows:

{
    "data": {
        "686cc1b1-cfdc-425d-9b93-c99290f0d35e": {
            "name": "Screenshot from 2022-06-27 23-29-29",
            "file_name": "Screenshot-from-2022-06-27-23-29-29.png",
            "uuid": "686cc1b1-cfdc-425d-9b93-c99290f0d35e",
            "preview_url": "",
            "original_url": "http://app.test/storage/media/25/Screenshot-from-2022-06-27-23-29-29.png",
            "order": 1,
            "custom_properties": [],
            "extension": "png",
            "size": 10546
        }
    }
}

but when I use filters I get empty array.

1 Answers1

2

You have to retrieve single media, then you can chain property name

$gallery->getMedia('default')[0]->name;

or

$gallery->getFirstMedia('default')->name;

If you want to return json with name and original_url field for every media, that can be achieved by using API resource, something like this:

$images = $gallery->getMedia('default');

return MediaResource::collection($images);

and in MediaResource class you have:

public function toArray($request)
{
    return [
        'name' => $this->name,
        'original_url' => $this->original_url
    ];
}
Cole Cokic
  • 36
  • 3
  • This is one approach. I was just trying to use the filters parameter that getMedia() method has as second parameter. There should be a purpose for it right? – Prabesh Guragain Jul 10 '22 at 01:53
  • Honestly, I didn't find an example for this in docs. You can take a look at this github issues https://github.com/spatie/laravel-medialibrary/issues/5 https://github.com/spatie/laravel-medialibrary/issues/613 https://github.com/spatie/laravel-medialibrary/issues/1228 . Maybe it can help you. – Cole Cokic Jul 10 '22 at 10:53