kalnoy/nestedset
Laravel Eloquent implementation of the Nested Set model for storing hierarchical data. Manage trees with fast reads: add, move, delete nodes, retrieve ancestors/descendants, build menus, and handle multiple roots with scoped trees, all via familiar model methods.
Start by installing the package: composer require kalnoy/nestedset. Add the HasNestedSet trait to your model (e.g., Category), then run Schema::create('categories', fn (Blueprint $table) => $table->nestedSet()->id()); in a migration. Create the first root node via Category::create(['name' => 'Root']), and append children using $root->appendNode(['name' => 'Electronics']). The most immediate use case is building navigational menus or category hierarchies—fetch all children with $category->getAllChildren() or load descendants efficiently via Category::with('descendants')->get().
Leverage the HasNestedSet trait for expressive tree operations: children, parent, siblings, ancestors, and descendants. Use eager loading wisely—with('descendants') avoids N+1 for large trees, but children is better for shallow-depth queries (e.g., breadcrumbs). Apply scoping to host multiple independent trees (e.g., per-tenant categories) with nestedSetScope($tenantId) before any queries. When synchronizing tree state from a frontend (e.g., drag-and-drop UI), use rebuildFromTree($array) to intelligently create, update, or prune nodes by primary key. Always use structural methods like appendToNode() or insertBeforeNode() instead of manual save()—they properly renumber lft/rgt values internally.
⚠️ Never modify lft/rgt directly—even trivial reads/modifications like $node->lft++ corrupt the tree structure; always rely on trait methods.
⚠️ getAllChildren() performs a full subtree scan—avoid it for deep hierarchies; use descendants()->limit() or recursive pagination instead.
⚠️ Scoping must be set before querying tree context (e.g., in middleware), or you risk cross-tree contamination.
💡 Prefer isRoot(), isLeaf() over manual lft == 1 checks—they’re cleaner and future-proof.
💡 For soft-deletable trees, combine HasNestedSet with SoftDeletes; the package auto-adjusts tree boundaries on soft-delete.
💡 Upgrade safely from v4.x: rename legacy methods (e.g., appendTo → appendToNode), but trait overrides minimize breaking changes.
💡 Validate tree integrity with validateTree() and fix structural drift via fixTree()—especially useful after raw DB edits or migrations.
How can I help you explore Laravel packages today?