PHP code example of tetthys / eloquent-hierarchy

1. Go to this page and download the library: Download tetthys/eloquent-hierarchy 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/ */

    

tetthys / eloquent-hierarchy example snippets


use Illuminate\Database\Eloquent\Model;
use Tetthys\EloquentHierarchy\Concerns\HasHierarchy;

class Category extends Model
{
    use HasHierarchy;

    // Optional: override the parent FK via a constant
    // public const HIERARCHY_PARENT_FOREIGN_KEY = 'parent_id';

    protected $fillable = ['name', 'parent_id'];
}

Schema::create('categories', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->unsignedBigInteger('parent_id')->nullable()->index();
    $table->timestamps();
});

$root = Category::create(['name' => 'Root']);
$child = Category::create(['name' => 'Child', 'parent_id' => $root->id]);

$child->hasParent();   // true (O(1), no query)
$root->hasChildren();  // true (EXISTS query)

$child->parent;        // BelongsTo relation (Category)
$root->children;       // HasMany relation (Collection<Category>)
$child->depth();       // 1

$leaf = Category::create(['name' => 'Leaf', 'parent_id' => $child->id]);

$leaf->depth();                // 2
$leaf->ancestors()->all();     // [Child, Root]
$leaf->ancestorIds()->all();   // [child_id, root_id]

$root->isAncestorOf($leaf);    // true
$leaf->isDescendantOf($root);  // true

// Limit how far to walk upward
$leaf->ancestors(1)->all();    // [Child]

$root->descendantsExist();        // true if any descendant exists
$root->descendantsExist(1);       // true if any direct child exists
$root->descendantsExist(2);       // true if child or grandchild exists

$ids = $root->descendantIds()->all();     // [child_id, grandchild_id, ...]
$ids = $root->descendantIds(1)->all();    // only depth=1

// Stream IDs level-by-level (no big arrays in memory)
foreach ($root->descendantIds() as $id) {
    // process each descendant id
}

// Materialize models (keeps level-order)
$models = $root->descendants(['id', 'name']);  // Collection<Category>

Category::roots()->get();   // parent_id IS NULL
Category::leaves()->get();  // no children

class Category extends Model
{
    use HasHierarchy;

    public const HIERARCHY_PARENT_FOREIGN_KEY = 'parent_uuid';
}

class Category extends Model
{
    use HasHierarchy;

    protected function parentForeignKeyName(): string
    {
        return 'parent_uuid';
    }

    protected function ownerKeyName(): string
    {
        return 'uuid';
    }
}

src/
  Concerns/
    HasHierarchy.php            # The trait
  Sql/
    descendant_ids_cte.sql      # CTE for collecting descendant IDs
    descendants_exist_cte.sql   # CTE for existence probe (LIMIT 1)