1. Go to this page and download the library: Download nevadskiy/laravel-tree library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
nevadskiy / laravel-tree example snippets
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Nevadskiy\Tree\AsTree;
class Category extends Model
{
use AsTree;
}
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->ltree('path')->nullable()->spatialIndex();
$table->timestamps();
});
Schema::table('categories', function (Blueprint $table) {
$table->foreignId('parent_id')
->nullable()
->index()
->constrained('categories')
->cascadeOnDelete();
});
}
public function down(): void
{
Schema::dropIfExists('categories');
}
};
$table->string('path')->nullable()->index();
$root = new Category();
$root->name = 'Science';
$root->save();
$child = new Category;
$child->name = 'Physics';
$child->parent()->associate($root);
$child->save();
echo $category->parent->name;
foreach ($category->children as $child) {
echo $child->name;
}
foreach ($category->ancestors as $ancestor) {
echo $ancestor->name;
}
$ancestors = $category->ancestors()->get();
$hierarchy = $category->joinAncestors();
foreach ($category->descendants as $descendant) {
echo $descendant->name;
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Nevadskiy\Tree\AsTree;
use Nevadskiy\Tree\Relations\HasManyDeep;
class Category extends Model
{
use AsTree;
public function products(): HasManyDeep
{
return HasManyDeep::between($this, Product::class);
}
}