Support the ongoing development of Laravel.io →
posted 10 years ago
Database

Hello, how can i make category tree's like:

Category 1
  category 1.1
        category 1.1.1
Category 2 
  category 2.1
        category 2.1.1

Every category is entity (model, and has a table in database)

As you can see i need categories with depth, how can i do that using relatioships such as many to many?

Last updated 3 years ago.
0

Your category table should be like this: id, parent_id, category_name. Whereas parent_id shows where that category is. For example:

id, parent_id, category_name

1,0,Category 1

2,1,category 1.1

3,2,category 1.1.1

4,0,Category 2

5,4,category 2.1

6,5,category 2.1.1

Every cat. has its unique id, and its parent's id (if its 0 there is no parent)

With this structure if you add a new sub-cat. under "Category 1", sub-cat. gets 7 as id, and also gets 1 as parent_id.

Last updated 3 years ago.
0

Thanks, so in my Category model i should write something like this:

    public function subcats()
    {
        return $this->belongsToMany('Category', 'parent_id');
    }

that's it?

Last updated 3 years ago.
0

I'm new at Laravel, so I'm not sure about that :) But the algorithm is OK :)

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.