Is Nested GroupBy supported in Laravel?

Viewed 69

I have a categories table with the fields "id", "category_id", "name" where "category_id" is the id of the parent category. My requirement is that I need to group the categories like below.

Europe
 - England
Asia
 - India
   - Kerala
     - Kochi

Note - Here Europe,England,Asia,India,Kerala,Kochi are categories. Asia is the parent category of India and India is the parent category of Kerala and Kerala is the parent category of Kochi.

Is there some nested groupBy solution?

1 Answers

Assuming that it's a one-to-many self-referencing relationship i.e. one category can only belong to some other category (single parent)

And your Category model should look something like this:

public function parent() {
   return $this->belongsTo('App\Category');
}

public function children() {
   return $this->hasMany('App\Category');
}

In your main blade template, you have:

  <ul class="navbar-nav">
       @foreach ($menu_items as $item)
             @include('menu', $item)
       @endforeach
  </ul>

Where $menu_items is the list of all parent categories ( categories where category_id is null or 0 )

And your menu blade template:

@if ( $item->children->isNotEmpty() )
<li class="nav-item {{ $item->parents->isNotEmpty() ? 'dropdown-submenu' : 'dropdown' }}">
    <a class="nav-link dropdown-toggle" href="{{ $item->slug ? url($item->slug) : 'javascript:void(0);' }}" id="navbarDropdown{{ $item->id }}" role="button" data-toggle="hover">
        {{ $item->title }}
    </a>

    <ul class="dropdown-menu" aria-labelledby="navbarDropdown{{ $item->id }}">
        @foreach ($item->children as $item)

            @include('menu', $item)

        @endforeach
    </ul>
@else
<li class="nav-item">
    <a class="nav-link" href="{{ $item->slug ? url($item->slug) : 'javascript:void(0);' }}">{{ $item->title }}</a>
@endif
</li>

I literally pasted this code from a project I worked on recently to give you an idea about nested drop-down, you've to work on the styling part yourself. But this code is enough to give you a proper understanding.

PS: this all untested. let me know if something doesn't work

Related