1

This question is in relation to: Group by in Laravel 5

Essentially, what I have have is a series of "Groups" and each group can have a as many child groups as they want. So it could look something like this:

  • Group 1
    • Group 1 Child
      • Group 1's child
        • Group 1 1's Child
  • Group 2

At the moment, I am only able to display the group, and their children, using:

    <ul>
@foreach($contents as $content)
  <li>{{$content->title}}</li>
  @if($content->children->count() > 0)
    <ul>
      @foreach($content->children as $childContent)
        <li>{{$childContent->title}}</li>
      @endforeach
   </ul>
  @endif
@endforeach
</ul> 

If I want to add more layers of children, I have to code this, with another if statement as well as a foreach statement. Obviously this is not practical when a group has n^3,... number of children.

Is there a dynamic, while-loop approach to solving this problem? Any help would be greatly appreciated!!

Community
  • 1
  • 1
Phorce
  • 4,424
  • 13
  • 57
  • 107

1 Answers1

1

What you need is a recursive partial - a one that would load itself as long as there are some more group levels to be displayed.

// list_group.blade.php
<li>
  {{ $content->title }}
  @if($content->children->count() > 0)
    <ul>
      @foreach($content->children as $childContent)
        @include('list_group', array('content' => $childContent))
      @endforeach
    </ul>
  @endif
</li>

//in your template 
<ul>
  @foreach($contents as $content)
    @include('list_group', array('content' => $content))
  @endforeach
</ul>
jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107