In this tutorial, I am going to share with you how to create category tree view structure in Laravel.
- Migration
- Model
- Show tree data structure in view
- Get path for node
In migrate
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('parent_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
In model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
// One level child
public function child()
{
return $this->hasMany(Category::class, 'parent_id');
}
// Recursive children
public function children()
{
return $this->hasMany(Category::class, 'parent_id')
->with('children');
}
// One level parent
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id');
}
// Recursive parents
public function parents() {
return $this->belongsTo(Category::class, 'parent_id')
->with('parent');
}
public function getPathAttribute()
{
$path = [];
if ($this->parent_id) {
$parent = $this->parent;
$parent_path = $parent->path;
$path = array_merge($path, $parent_path);
}
$path[] = $this->name;
return $path;
}
}
Show tree data structure in view
<link href="path/to/jquery.treetable.css" rel="stylesheet" type="text/css" />
<script src="path/to/jquery.treetable.js"></script>
<table id="category_table">
@foreach($categories as $category)
<tr data-tt-id="{{$category->id}}"
{{$category->parent_id ? "data-tt-parent-id={$category->parent_id}" : ""}}>
<td>
@if ($category->childs->isEmpty())
<input type="radio" id="category_id" name="category_id" value="{{$category->id}}">
@endif
{{ $category->name }}
</td>
</tr>
@endforeach
</table>
<script>
$("#category_table").treetable({ expandable: true });
</script>
Like this
Get path for node
<td>{{ implode(' > ', $category->path) }}</td>
Like this
Ref:
Managing Hierarchical Data in MySQL
Laravel Unlimited Hierarchical Category Tree View
jQuery treetable