DEV Community

Cover image for How to create a nested-list of categories in Laravel blade
musthafa-advance
musthafa-advance

Posted on

How to create a nested-list of categories in Laravel blade

Its really difficult to iterate and show Parent child Categories tree or listing in Laravel, sometimes it affect websites performance,
To solve this problem we need to use a recursive blade.
Just follow this steps to make it happen

  1. First of all we need to get all the categories and childs.

To get all categories with childs, create a childs
function inside the Category model

 public function childs()
    {
        return $this->hasMany(Category::class, 'parent_id', 'id');
    }

this function will return all categories with its childs
then fetch categories in your controller like below code

$categories = Category::whereNull('parent_id')->with('childs')->get();

2.inside your blade

@foreach($categories as $category)
  <li>
   {{{ $category->category_name }}}
   @if(count($category->childs))
   @include('category-partial ',['childs' => $category->childs])
   @endif
  </li>
@endforeach

3.Create category-partial.blade which we are using to loop each of the category so that we can show the category without a limit

<ul>
@foreach($childs as $child)
    <li>
 <a href="{{{  url('search/?category='.$child->category_name.'-'.$child->id.'&q=') }}}">{{{ $child->category_name }}}</a>
 @if(count($child->childs))
 @include('admin.managechild',['childs' => $child->childs])
 @endif
  </li>
@endforeach
</ul>

Top comments (4)

Collapse
 
monaye profile image
Monaye Win

how do you limit the numbers of categories(total of both parent and child) to show on the page?

Collapse
 
alinchindea profile image
Alin Chindea

you paginate. where you do $categories = Category::whereNull('parent_id')->with('childs')->get(); you can do $categories = Category::whereNull('parent_id')->with('childs')->paginate(x); where x is the number of items you want to show on page.

Collapse
 
monaye profile image
Monaye Win

that will do pagination based on the count of the parent_id category.
I wanted to display the categories with a hierarchy. Ended up with this:

$categories = Category::where('level', 0)->with('descendants')->get()->flattenTree()->paginate(15);
Enter fullscreen mode Exit fullscreen mode

Image of hierarchy

Collapse
 
monaye profile image
Monaye Win

that will do pagination based on the count of the parent_id category.
I wanted to display the categories with a hierarchy. Ended up with this:

$categories = Category::where('level', 0)->with('descendants')->get()->flattenTree()->paginate(15);
Enter fullscreen mode Exit fullscreen mode