2

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 .

SyedKhizer
  • 241
  • 1
  • 5
  • 14

1 Answers1

2

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();
N69S
  • 16,110
  • 3
  • 22
  • 36
  • It Worked for my case actually I will surely have category before fetching the products so the first one will be useful for me but yeah second one is also good approach to avoid errors . – SyedKhizer Jun 17 '21 at 08:57
  • @SyedKhizer Actually, i usualy use the first one to avoid errors. it's a good thing to know if something is wrong in the inputs. – N69S Jun 17 '21 at 08:59