Laravel Nested Set
Effective tree structures for Laravel Eloquent using the Nested Set Model
Repository Health
Technical Analysis
Laravel Nested Set (kalnoy/nestedset) brings the Nested Set Model to Laravel’s Eloquent ORM, letting you store and query deeply hierarchical data such as categories, menus, and organizational trees inside a single relational table. It adds a trait, a custom query builder, and dedicated relations so that ancestors, descendants, siblings, and depth can be fetched with fast, index-friendly queries.
Rather than issuing recursive queries, the package maintains left/right boundary values on each row so that entire subtrees can be retrieved with simple range comparisons. It integrates transparently with Eloquent models, supports scoping, soft deletes, tree rebuilding from arrays, and consistency checking and fixing.
What You Get
- A NodeTrait you add to any Eloquent model to make it a tree node
- Ancestor, descendant, sibling, parent, and children relationships that can be eagerly loaded
- A custom query builder with constraints like whereIsRoot, whereDescendantOf, and withDepth
- Tree building, rebuilding from arrays, and consistency checking/fixing helpers
- Support for scoping, soft deletes, and deferred structural operations
Common Use Cases
- Storing and rendering multi-level shop categories or product taxonomies
- Building nested navigation menus with breadcrumbs from ancestors
- Modeling organizational charts, comment threads, or folder hierarchies
Under The Hood
Architecture - The package centers on a NodeTrait (src/NodeTrait.php, ~1,240 lines) that boots Eloquent model events to defer structural operations until save, plus a custom QueryBuilder (~1,100 lines) extending Eloquent’s builder with nested-set-aware constraints. Dedicated AncestorsRelation and DescendantsRelation classes extend a shared BaseRelation, and a Collection subclass converts flat result sets into parent/children trees via toTree(). A thin NestedSetServiceProvider registers the package with Laravel.
Tech Stack - Pure PHP targeting PHP 8.0+, depending only on illuminate/support, illuminate/database, and illuminate/events (Laravel 13+ per the latest release). Tests run on PHPUnit. There is no external runtime beyond Eloquent itself, keeping the footprint minimal.
Code Quality - The tests/ directory holds substantial coverage (NodeTest.php ~1,000 lines and ScopedNodeTest.php ~237 lines) exercising insertion, movement, scoping, and consistency behavior against fixture models. Source files use PHPDoc annotations, consistent naming, and clear separation between trait, builder, and relations.
API Design - The public API is fluent and Laravel-idiomatic: Category::descendantsOf($id), $node->appendToNode($parent)->save(), withDepth(), and defaultOrder() read naturally alongside standard Eloquent. The README is thorough with copy-paste examples for every operation, so getting started requires only adding the trait and the lft/rgt columns.