michaelorenda/laravel-recursive-relations

Recursive parent-child traversal for Eloquent models.

Installs: 2

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/michaelorenda/laravel-recursive-relations

v1.0.3 2025-11-29 15:41 UTC

This package is auto-updated.

Last update: 2025-11-29 15:41:43 UTC


README

Powerful recursive parent–child relationships for Laravel 12+

A lightweight, framework-native package for building hierarchical data structures such as:

  • Organization Units
  • Categories & Subcategories
  • File Trees
  • Product & Menu Structures
  • Multi-level Comment Threads
  • Any recursive / tree-based domain

πŸš€ Features

  • Pure nested tree output via tree()
  • Flat descendant lists via descendants()
  • Unlimited or depth-limited recursion
  • Guaranteed no repetition / no duplicated nodes
  • Automatic ancestry resolution (ancestors(), root())
  • Optional caching layer via HasRecursiveCache
  • Fully compatible with Laravel 12+
  • Zero dependencies; Eloquent-powered
  • Works with any model

πŸ“¦ Installation

composer require michaelorenda/laravel-recursive-relations

Laravel will auto-discover the service provider.

🧩 Usage Example

1. Add the Trait

use MichaelOrenda\LaravelRecursiveRelations\Traits\HasRecursiveRelations;

class Category extends Model
{
    use HasRecursiveRelations;

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

2. Required Migration

$table->unsignedBigInteger('parent_id')->nullable()->index();

🌳 Building Trees

Pure Nested Tree

$tree = Category::find(1)->tree();

Produces:

[
  {
    "id": 2,
    "name": "Child",
    "children": [
      { "id": 7, "name": "Grandchild", "children": [] }
    ]
  }
]

βœ”οΈ No duplication
βœ”οΈ No repeated branches
βœ”οΈ Perfect hierarchy

Flat Descendants

$flat = Category::find(1)->descendants();

πŸ”— Ancestry Tools

$node->parent;
$node->children;
$node->ancestors(); 
$node->root();

βš™οΈ Customizing Keys

protected static function recursiveConfig(): array
{
    return [
        'parent_key' => 'parent_unit_id',
        'local_key'  => 'unit_id',
    ];
}

πŸ“š API Documentation

See API_DOCS.md

πŸ” Security

See SECURITY.md

🀝 Contributing

PRs welcome! Follow PSR-12 and include tests.

πŸ“„ License

MIT β€” Free for personal and commercial use.

Last updated: 2025-11-29