I have a function where I am passing the category id and based on that I want to fetch all the products .
Here is a structure of my db
Category db:
category_name
Product db:
product_name;
category_product:
category_id;
product_id;
Below are the relations between them
In Product :
public function categories()
{
return $this->belongsToMany(Category::class);
}
In Category:
public function products()
{
return $this->belongsToMany(Product::class);
}
I have tested multiple queries but nothing worked for my case .
You can do it in two different ways
Indirect way wich verifies that the category exists (2 queries)
$category = Category::with('products')->findOrFail($categoryId);
// you can also do without the with(); only one id, so no benefit for the eager load
// $category = Category::findOrFail($categoryId);
$products = $category->products;
Direct way, wich will return an empty collection if the category doesnt exist (but no message) (1 query)
$products = Product::whereHas('categories', function($qbCategory) use($categoryId) {
$qbCategory->where('id',$categoryId);
})->get();