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

nillie_io's avatar

Get media collection using spatie media library (inertia js)

Hi all,

Original Post: Similar Question https://laracasts.com/discuss/channels/javascript/get-media-collection-spatie-media-library-using-inertia-js

In the above thread, the suggestion was to use create a resource in order to pull in the spatie media (in my case, profile images). Is there an alternative to this? I do not like how when using a resource everything is wrapped by "data", which makes makes the props to my component less clear. For example, my "Accounts" props is no longer an array in my component. It becomes an object named Accounts with a property data that contains all of the account data.

*Bonus. I would be so, so appreciative if I could also learn how to select certain fields, like preview_image, while ignoring others, like size and mime type.

AccountController

    public function index()
    {
        return Inertia::render(
            'Account/Index',
            [
                'accounts' => AccountResource::collection(Account::query()
                    ->with('user')
                    ->visibleTo(Auth::user())
                    ->orderBy('created_at')
                    ->get())
            ]
        );
    }

AccountResource

 public function toArray($request)
    {
        return [
            'id' => $this->id,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'bg_color' => $this->bg_color,
            'media' => $this->getFirstMediaUrl('account_images'),
        ];
    }

0 likes
1 reply
aleahy's avatar

Getting rid of data is in the laravel docs: https://laravel.com/docs/9.x/eloquent-resources#data-wrapping Just add JsonResource::withoutWrapping(); to the boot method of your AppServiceProvider and it won't be there. It will be there if you paginate though.

And the best way to implement your Bonus section is through a resource. Just specify which attributes you want to return on a MediaResource and don't include the ones you don't want.

//MediaResource
public function toArray($request)
{
   return [
      'preview_image' => $this->getUrl('preview'),
   ];
}
//AccountResource
public function toArray($request)
{
   return [
      'profile_image' => MediaResource::make($this->whenLoaded('profileImage')),
   ];
}

Please or to participate in this conversation.