'How to get All Child Category Product under Parent Category id in laravel
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 ?
Solution 1:[1]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ayman Elmalah |
