Laravel: Show products of all subcategories

45 views Asked by At

I have a main category and quite a few sub-categories within that main category. When I enter the main category, I want to list all products of all sub-categories that belong to the main category.

What i do

Model

class Category extends Model
{
   public function children()
   {
     return $this->hasMany(Category::class, 'parent_id', 'id');
   }

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id', 'id');
    }

    public function products()
    {
        return $this->belongsToMany(Product::class, 'product_category', 'category_id');
    }
}

Controller

class FrontedController extends EcommerceController
{
   public function index()
   {
      $categories = Category::where('parent_id', 1)->where('id', '<>', 1)->get();
     
      return view('ecommerce::fronted.pages.category',['categories' => $categories,                     
                ]);
   }
}

The problem is that I don't know how to recursively enter all subcategories. My code only displays products for the current category.

Anyone know solution? Thanks!

1

There are 1 answers

0
Ali SSN On

if you use Mysql 8, can use this packge:

staudenmeir/laravel-adjacency-list

no need any change in your structure

or other version :

lazychaser/laravel-nestedset

need add 2 column _lft,_rgt to your table