I use this package to create trees. You just give it the models as a collection and it does it for you (just just need to set up a few methods on the model)
Nov 4, 2021
3
Level 4
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/
Please or to participate in this conversation.