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

Fluber's avatar

Laravel media Library optimize query

Hello. On Main page I have list of shops. On every shop I have a banner. If I have 15 shops on page, I have 25+ query. And most big query this is query of spatie/MediaLibrary. On model Shop I have attribute:

protected $appends = ['photo_url'];

public function getPhotoUrlAttribute()
{
    if ($this->getMedia('banners')->last()) {
        return $this->getMedia('banners')->last() !== null ? $this->getMedia('banners')->last()->getUrl('banners') : null;
    }
}

On controller:

$shops = Shop::paginate(15);

In blade:

@foreach($shops as $shop)
....
<img src="{{ $shop->photo_url }}">
@endforeach

For every shop media Library do 1 one query, example:

select * from `media` where `media`.`model_id` = 3 and `media`.`model_id` is not null and `media`.`model_type` = 'App\Models\Shop'

    select * from `media` where `media`.`model_id` = 4 and `media`.`model_id` is not 
    null and `media`.`model_type` = 'App\Models\Shop'

How I can optimize these queries, and do all in one query with shop paginate?

0 likes
1 reply
Braunson's avatar

I'd suggest eager loading the media for the shops so you don't have to make a query per shop.\

$shops = Shop::with('media')->paginate(15);
3 likes

Please or to participate in this conversation.