Search code examples
laravelcategories

Laravel - Sub-categories display under Main categories


Hi there
I have one problem with categories and sub-categories
I have table like:

ID----- Name---- ParentID
1 ------- A ---------- 0
2 ------- B ---------- 0
3 ------- C ---------- 1
I have showing A B C ok . But i need it will show like this:
A
-- C
B

Just have problem with dont find the way to do this (to make sub categories under parent)

Note: i have success with make query in Views, but i think its not good .
I would like to find better way
Thank you very much


Solution

  • Using Eloquent you can use a hasMany() relationship to relate the table to itself.

    Try creating a new method on your model, like so:

    class Category extends Eloquent 
    {
    
        ...
    
        public function children()
        {
            return $this->hasMany('Category','ParentId');   
        }
    }
    

    Then you should be able to get a list of sub categories for any given ID.

    $categories = Category::where('ID','=','1')->with('children')->get();
    

    Alternatively, the query suggested by deczo in the comments is a lot simpler, I would recommend using this instead.

    Category::with('children')->find(1);