Reputation: 587
How to create multilevel Category tree from same table in Laravel. I may have 2 level categories or may be up to 5th level Subcategories and I want this dynamic in Laravel.
For example-
Category 1
|_ Subcat 1-1
|_ Subcat 1-2
Category 2
|_Subcat 2-1
| |_Subcat 2-1-1
| | |_ Subcat 2-1-1-1
| | |_ Subcat 2-1-1-2
| |
| |_Subcat 2-1-2
|
|_Subcat 2-2
Category 3
Upvotes: 0
Views: 391
Reputation: 847
You can introduce parent_id column in your table
For items at the first level , the the id and parent_id is simillar
CategoriesTable { id ,name,parent_id }
Here is how the data is stored in the table
id , name , parent_id
1 , Books , 1
2 , Clothes ,2
3 , counterbook,1
4 , jeans , 2
5 , cars,5
The chain can go on and on , so in your foreach loop you have put an if id = parent_id then you know to determine 1st level
Upvotes: 1