Laravel get all products from infinity nested categories

I have the category model where each category can be general or nesting.


To get children of category and all nested children of category use relation with recursion

public function children()
    return $this->hasMany('AppModelsCategory', 'parent_id', 'id');

public function allChildren()
    return $this->children()->with('allChildren');

And relation for products
    public function product()
    return $this->belongsToMany('AppModelsProduct', 'categories_products');

How can I get all products from base category and all nested categories?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you don’t care about performance something like this should work (not tested) but it might obviously generate many queries in case you have very complex tree of categories.

$products = Category::getAllProducts($categoryId);

public static function getAllProducts($categoryId, $products = null)
  if ($products === null) {
     $products = collect();   
  $category = Category::find($categoryId); 
  $products = $products->merge($category->product);
  $category->children->each(function($child) {
      $products = self::getAllProducts($child->id, $products);

  return $products;

As alternative you could find first all the categories and then products that belong to those categories assuming you won’t get hundreds of categories because it could lead to PDO bindings problems if you don’t use raw queries.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x