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
- 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
composer require michaelorenda/laravel-recursive-relationsLaravel will auto-discover the service provider.
use MichaelOrenda\LaravelRecursiveRelations\Traits\HasRecursiveRelations;
class Category extends Model
{
use HasRecursiveRelations;
protected $fillable = ['name', 'parent_id'];
}$table->unsignedBigInteger('parent_id')->nullable()->index();$tree = Category::find(1)->tree();Produces:
[
{
"id": 2,
"name": "Child",
"children": [
{ "id": 7, "name": "Grandchild", "children": [] }
]
}
]✔️ No duplication
✔️ No repeated branches
✔️ Perfect hierarchy
$flat = Category::find(1)->descendants();$node->parent;
$node->children;
$node->ancestors();
$node->root();protected static function recursiveConfig(): array
{
return [
'parent_key' => 'parent_unit_id',
'local_key' => 'unit_id',
];
}See API_DOCS.md
See SECURITY.md
PRs welcome! Follow PSR-12 and include tests.
MIT — Free for personal and commercial use.
Last updated: 2025-11-29