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
Requires
- php: ^8.2
- illuminate/support: ^12.0
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