wim91's avatar
Level 2

How to group products by parent category with unlimited descendants?

Hello everyone. I have a category table where each parent category has an unlimited number of children. Products can only appear in the very last child category. How can I group products by parent category?

1 like
1 reply
vincent15000's avatar

I have a similar situation.

Here is my code.

And I get the categories with the tables in the controller.

public function categories(): Collection
{
    return Category::select('id', 'name', 'description', 'category_id')
        ->with('categories', 'tables')
        ->whereNull('category_id')
        ->orderBy('name')
        ->get();
}

public function tables(): Collection
{
    $tables = new Collection;

    if ($this->selectedCategory) {
        $tables = $this->selectedCategory->subTables();
    } else {
        $tables = Table::orderBy('name')->get();
    }

    return $tables;
}

The only problem is that if I have 10 different categories and each one has also 10 subcategories, ... there is a big N+1 problem.

For my project it doesn't matter because there are very few categories, but it can be a problem for a lot of categories.

Please or to participate in this conversation.