Garet
2 months ago

Eloquent 'with' still resulting in multiple queries

Posted 2 months ago by Garet

I have a product. Each product can have one image. Images are also used by other things (users, categories, etc) so I am using a morphable relation.

In my product model I have:

public function image()
{
    return $this->morphOne(Image::class, 'imageable');
}

My image model has the following method:

public function src($size = 'small')
{
    $available_sizes = $this->sizes;
    // Some login here to determine if requested size exists
    return something;
}

Then I can get all products along with their image like this:

$products = Product::with('image')->get()

This results in 2 queries, one to fetch the products, and one to fetch the images. Perfect so far.

However, in my blade template I end up with multiple queries to the images table. If I have 100 products then there are 100 queries on the images table:

@foreach ($products as $product)
<img src="{{ $product->image->src() }}" />
@endforeach

How can I avoid the additional queries?

Thanks,

Please sign in or create an account to participate in this conversation.