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

Benounnas Oussama's avatar

Laravel Spatie Media query

Hello, i'm working with Laravel Spatie media library. when i search the media using a simple where() eloquent query, i get an empty collection, i tried using id it worked, i found a workaround which is:

$mediaEmpty = $product->getMedia()->isEmpty();
// i had to convert it again to sql
$sizeEmpty = $product->getMedia()->toQuery()->where('file_name', 'like', '%800x800%')->get()->isEmpty();

if (!$mediaEmpty && !$sizeEmpty) {
     $product->image = $product->getMedia()->toQuery()->where('file_name', 'like', '%800x800%')
        ->get()[0]->getFullUrl();
 // the product has many images with different sizes where i wanted to keep the quality clearn (e-commerce)
 } else {
      $product->image = '';
    }

i checked their documentation, i can't find filters of the media, is it the best way to convert it again to and sql? any other way to properly get items based on the name? thnx!

0 likes
1 reply
Benounnas Oussama's avatar

nevermind, may be it can be done with filter() method :

Model::findOrFail($this->product_id)->getMedia()
->filter(function ($value, $key) use ($size) {
return  str_contains(data_get($value, 'file_name'), $size);   
})

Please or to participate in this conversation.