3

In categories table

categories

id categoryName parentId
1 Men's Fashion NULL
2 T-Shirt 1
3 Pants 1
4 Shoes 1

And another table is

products

id productName productCategoryId
1 A 2
2 B 3
3 C 4

And My Menu List is

  • Men's Fashion
    • A
    • B
    • C

When i click "A" then i can show all "A" category product. That can i already solved. But i can't show all products under "Men's Fashion". (In "Men's Fashion" here show "A", "B", and "C" subcategory product.) How can i solve this ?

1 Answers1

2

In product model you need to have a relation between product and category like this

public function category(){
    return $this->belongsTo(Category::class);
}

so to get products for category 1 the query will be like

$products = Product::whereHas('category', function ($q) {
         $q->where('parentId', 1)
})->get();
Ayman Elmalah
  • 321
  • 1
  • 5