PHP code example of indigoram89 / laravel-nested-set

1. Go to this page and download the library: Download indigoram89/laravel-nested-set 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/ */

    

indigoram89 / laravel-nested-set example snippets




namespace App\Models;

use Indigoram89\NestedSet\Models\NestedSetModel;

class Category extends NestedSetModel
{
    protected $table = 'categories';
    
    protected $fillable = ['name', 'slug'];
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Indigoram89\NestedSet\Traits\NestedSetTrait;

class Category extends Model
{
    use NestedSetTrait;
    
    protected $fillable = ['name', 'slug'];
}

Schema::create('categories', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('parent_id')->nullable()->index();
    $table->integer('lft')->default(0)->index();
    $table->integer('rgt')->default(0)->index();
    $table->unsignedInteger('depth')->default(0);
    $table->string('name');
    $table->string('slug')->nullable()->index();
    $table->timestamps();
    
    $table->index(['lft', 'rgt']);
    $table->index(['parent_id', 'lft']);
});

$root = Category::create(['name' => 'Root Category']);
$root->makeRoot();

$child = Category::create(['name' => 'Child Category']);
$child->makeChildOf($parent);

// Переместить слева от узла
$node->moveToLeftOf($target);

// Переместить справа от узла
$node->moveToRightOf($target);

// Сделать дочерним узлом
$node->makeChildOf($parent);

// Получить всех потомков
$descendants = $node->getDescendants();

// Получить всех предков
$ancestors = $node->getAncestors();

// Получить прямых потомков
$children = $node->getChildren();

// Получить родителя
$parent = $node->getParent();

// Получить соседние узлы
$siblings = $node->getSiblings();

// Получить путь до узла
$path = $node->getPath();

// Получить все дерево
$tree = Category::query()->getTree();

// Является ли узел корневым
$node->isRoot();

// Является ли узел листом (без потомков)
$node->isLeaf();

// Проверка целостности дерева
$node->isValidNestedSet();

// Удалить узел с потомками
$node->deleteSubtree();

// Получить корневые узлы
Category::query()->roots()->get();

// Получить листья
Category::query()->leaves()->get();

// Получить узлы определенной глубины
Category::query()->withDepth(2)->get();

'models' => [
    [
        'name' => 'category',
        'class' => App\Models\Category::class,
        'label' => 'Категории',
        'description' => 'Управление категориями товаров',
    ],
    [
        'name' => 'menu',
        'class' => App\Models\MenuItem::class,
        'label' => 'Меню',
        'description' => 'Управление пунктами меню',
    ],
],

Route::prefix('nested-set')
    ->middleware(['web', 'auth', 'can:manage-trees'])
    ->group(function () {
        Route::get('/', [NestedSetWebController::class, 'index']);
    });

return [
    // Названия колонок
    'columns' => [
        'left' => 'lft',
        'right' => 'rgt',
        'depth' => 'depth',
        'parent_id' => 'parent_id',
    ],

    // Имя таблицы по умолчанию
    'table' => 'nested_sets',

    // Модели для веб-интерфейса
    'models' => [
        // Добавьте ваши модели здесь
    ],

    // Настройки производительности
    'cache' => [
        'enabled' => true,
        'ttl' => 3600,
        'prefix' => 'nested_set_',
    ],
];

$categories = Category::query()->roots()->get();

foreach ($categories as $root) {
    echo $root->name;
    
    foreach ($root->getChildren() as $child) {
        echo '-- ' . $child->name;
        
        foreach ($child->getChildren() as $grandchild) {
            echo '---- ' . $grandchild->name;
        }
    }
}

$category = Category::find($id);
$breadcrumbs = $category->getPath();

foreach ($breadcrumbs as $crumb) {
    echo $crumb->name . ' > ';
}

$model = new Category();
$model->rebuild();
bash
php artisan vendor:publish --tag=nested-set-config
bash
php artisan vendor:publish --tag=nested-set-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=nested-set-views
bash
php artisan vendor:publish --tag=nested-set-assets
bash
# Опубликовать всё
php artisan vendor:publish --provider="Indigoram89\NestedSet\NestedSetServiceProvider"

# Или по отдельности:
php artisan vendor:publish --tag=nested-set-config
php artisan vendor:publish --tag=nested-set-assets