Mubeenali's avatar

how to retrive a category and all it's child in tree structure same as all ecommerce sites ?

I have a table called categories.i stored data into it in such a manner if the category parent_id is 0 then it is the most parent category if category parent id is not 0 then obviously it is the child of anyone ...Means to say that i store the data into tree structure each category can be subcategory or may be sub sub category .Now i want to show them in navigation bar at frontend but i am not getting the actual logic to show them Any one please help me ..My category Model structure is givenbelow:

 id - primary key
category 
parent_id
slug
0 likes
4 replies
Sergiu17's avatar

Warning - recursive queries

class Category extends Model
{

    public function subCategories()
    {
        return $this->hasMany(Category::class, 'parent_id')->with('subCategories');
    }
$category = Category::find(1);
$category->subCategories();
Sergiu17's avatar
// recursive helper function
function generateCategories($categories)
{
    foreach ($categories as $category) {
        echo '<li>' . $category->name . '</li>';
        if (count($category->subCategories) > 0) {
            echo '<ul>';
                echo '<li>';
                    generateCategories($category->subCategories);
                echo '</li>';
            echo '</ul>';
        }
    }
}
$categories = Category::where('parent_id', 0)->get();

<ul>
    generateCategories($categories);
</ul>

Please or to participate in this conversation.