Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Laracast13's avatar

laravel hierarchical category tree view

Hello Want create category tree view.

This is post_categories where I can set parent ID for each category

Schema::create('post_categories', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('parent')->nullable(); 
            $table->mediumInteger('order')->nullable(); 
            $table->string('name')->nullable();
            $table->string('slug')->unique(); 
            $table->timestamps();
        });

I have problem display it.

For ex. If I have 2 level tree it is easy to display

Cat1
-sub cat1
-sub cat2

blade

@foreach($categories->where('parent', 0) as $category)
<div class="row py-1" style="border-bottom: 1px solid #dee2e6;">
    <div class="col-sm-1 pt-1"><strong>ID:</strong> {{$category->id}}</div>
    <div class="col-sm-4 pt-1"><strong>{{ __('i_Name') }}:</strong> {{$category->name}}</div>
    <div class="col-sm-4 pt-1"><strong>{{ __('i_Slug') }}:</strong> {{$category->slug}}</div>
</div>  
    @foreach($categories->where('parent', $category->id) as $subCategory)
    <div class="row py-1" style="border-bottom: 1px solid #dee2e6;">
        <div class="col-sm-1 pt-1 pl-4"><strong>ID:</strong> {{$subCategory->id}}</div>
        <div class="col-sm-4 pt-1"><strong>{{ __('i_Name') }}:</strong> {{$subCategory->name}}</div>
        <div class="col-sm-4 pt-1"><strong>{{ __('i_Slug') }}:</strong> {{$subCategory->slug}}</div>
    </div> 
    @endforeach 
@endforeach 

But when I have many level sub sub category , add foreach each time is bad solution

Cat1
-sub cat1
--sub sub cat1
---sub sub cat2
----sub sub sub cat3
-----sub sub sub sub cat4
Cat2
-sub cat1
--sub sub cat1
---sub sub cat2
----sub sub sub cat3
-----sub sub sub sub cat4

p.s. I search solution and everywhere find such posts, which display only 2 level tree https://www.tutsplanet.com/hierarchical-tree-view-category-example-in-laravel/

0 likes
3 replies
Laracast13's avatar

@Sinnbeck thanks. I want make it without package . Maybe someone can advise me what logic can use to solve my task

Sinnbeck's avatar

@www888 do a few steps

  1. load all the categories. Otherwise you can end up with the n+1
  2. Use a recursive function to convert the collection into a tree structure

That is how that package does it, so you can use it for reference

1 like

Please or to participate in this conversation.