Reputation: 21
I want to have a list of products that have id categories as a foreign key, but I don't want to have a query for each product, is there a smarter way to do it? The current code works but I don't think I'm doing it correctly, follow the code:
if($products){
$categories = [];
foreach($products as $product){
$categories[] = $product->categories()->first();
}
return view('products',[
'products' => $products,
'categories' => $categories
]);
}```
Upvotes: 0
Views: 45
Reputation: 1433
You can use Eager loading to load the categories of each products without looping through each one :
$products
if($products){
$products->with('categories')->get();
return view('products',$products);
}
$products
with extra constraints: if($products){
$products->with(['categories' => function ($query) {
$query->where('...');
}])->get();;
return view('products',$products);
}
Upvotes: 1
Reputation: 544
When you do it like this
$categories[] = $product->categories()->first();
$product->categories()
does a new instance of the query builder`.
If you want to access the relation with 1 query you need to refer ot it as a method
$product->categories
this way you will get a collection of all categories.
If you want all categories for a specific product do it like this;
$product = Product::find(1);
-> this is just example for getting a product with ID 1.
Then you need all categories of this product.
$product->categories
-> Categories is your relationship in the Product model, we are reffering to it as a METHOD
not as a FUNCTION
.
return view('products',[
'product' => $product,
'categories' => $product->categories
]);
Upvotes: 1