spatie / laravel-medialibrary

Associate files with Eloquent models
https://spatie.be/docs/laravel-medialibrary
MIT License
5.78k stars 1.08k forks source link

Media repository always returns an empty collection #3503

Closed michaeldzjap closed 10 months ago

michaeldzjap commented 10 months ago

I am trying to retrieve all media items for a model by using the following:

$model->getMediaRepository()->all();

I get the expected number of items when I execute the above command in tinker. However, when executing it as part of a JSON request I always get an empty array. After some digging in the source I traced the problem back to here. Since no form field name or collection name is set on the collection instance when calling the above statement an empty array will be returned when serialising the collection to JSON. A similar problem seems to happen with the toHtml method by the way.

The getMedia method doesn't have this problem, as it passes down the (default) collection name to the media collection object. So I can work around it for my purposes by creating a MediaResource class and passing the result of $model->getMedia() to it. Inside the media resource I can then select the attributes that I want to include in the response. Still wanted to report this, as I don't think this is intended behaviour.

freekmurze commented 10 months ago

Changing this now is a breaking change, but we'll improve this in a new major version.