Home > Software design >  spatie/laravel-medialibrary, filters on getMedia() function not working
spatie/laravel-medialibrary, filters on getMedia() function not working

Time:07-10

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.

CodePudding user response:

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
    ];
}
  • Related