Answer the question
In order to leave comments, you need to log in
How to simplify a database query?
There are 2 tables: products and images. In images, each entry contains the fk product_id and the images for the product.
The problem is that on the page for each product card (there are 20 of them) there is a separate request in images to get a picture.
How can you make only 1 request in images instead of 20?
//Controller
public function index() {
$products = Product::where('brand_id', 1)->limit(18)->get();
$brands = Brand::whereIn('id', [1, 3, 4, 10, 11, 12])->get();
return view('front.product.index', compact('products', 'brands'));
}
// Product model
public function images() {
return $this->hasMany(Image::class);
}
@foreach ($products as $product)
<img src="{{ $product->images->first()->img_one }}">
@endforeach
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question