Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message
Laravel Adjacency List

Laravel Adjacency List Laravel Package

staudenmeir/laravel-adjacency-list

Laravel Eloquent extension for recursive tree and graph relationships using SQL common table expressions. Traverse ancestors, descendants, and paths in adjacency-list data across MySQL, Postgres, SQLite, SQL Server, and more; supports one-to-many trees and many-to-many graphs.

View on GitHub
Deep Wiki
Context7

Recursive Laravel Eloquent relationships with CTEs

Frequently asked questions about Laravel Adjacency List
How do I install and set up Laravel Adjacency List for a tree structure like categories?
Run `composer require staudenmeir/laravel-adjacency-list` and add the `HasRecursiveRelationships` trait to your Eloquent model (e.g., `Category`). Define a parent relationship using `public function parent() { return $this->belongsTo(Category::class); }`, then use methods like `descendants()` or `ancestors()` to traverse the hierarchy. The package works with Laravel 5.5+ and requires no additional database setup.
Does this package support graphs (many-to-many relationships) or just trees?
Yes, it supports both trees (one-to-many) and graphs (many-to-many). For graphs, use `hasManyThrough` with the `HasRecursiveRelationships` trait and enable cycle detection if needed. Graphs require more configuration but allow complex hierarchies like org charts with multiple reporting lines. Trees are simpler and more performant for most use cases.
Which Laravel versions are officially supported, and how do I check compatibility?
The package supports Laravel 5.5 through 13.x, with version-specific releases (e.g., `1.26` for Laravel 13). Check the [compatibility table](https://github.com/staudenmeir/laravel-adjacency-list#versions) in the README. Always install the version matching your Laravel major version to avoid breaking changes. For example, use `^1.26` for Laravel 13.
Will this package work with my existing database schema, or do I need to add columns like `depth` or `path`?
No additional columns are required. The package uses SQL CTEs to recursively traverse relationships without materialized paths or nested sets. However, you can customize column names (e.g., `getDepthName()`) if your schema already uses `depth` or `path`. For graphs, ensure your pivot table supports the many-to-many relationship structure.
How do I optimize performance for deep hierarchies (e.g., 10+ levels) or large datasets?
Use `withMaxDepth($depth)` to limit recursion depth and avoid excessive memory usage. For very large trees, implement pagination with `cursor()` or chunking. The package leverages database-level CTEs, which are faster than application-side recursion, but deep hierarchies may still require indexing on the parent foreign key. Test with `withMaxDepth()` to find the optimal balance.
Can I use this package for threaded comments or forum replies where replies can have multiple parents?
Yes, threaded comments with multiple parents (graphs) are fully supported. Use the `HasRecursiveRelationships` trait with a many-to-many relationship (e.g., `belongsToMany` for replies). Enable cycle detection if comments can reference each other in loops. For simpler trees (one parent per reply), use `belongsTo` for better performance.
How do I handle cycle detection in graphs (e.g., preventing a node from being its own parent)?
Enable cycle detection by calling `enableCycleDetection()` on your model’s recursive relationship. This adds a SQL `WITH RECURSIVE` check to prevent infinite loops. For large graphs, this may impact performance, so test with `withMaxDepth()` to limit recursion. Cycles are automatically detected but not prevented—validate data at the application level if needed.
Is there a way to eager-load recursive relationships to avoid N+1 query problems?
Yes, use Laravel’s `with()` method to eager-load recursive relationships. For example, `Category::with('descendants')->find(1)` loads descendants in a single query. The package integrates seamlessly with Eloquent’s query builder, so you can use `with()` alongside other relationships. For graphs, eager-loading may be less efficient due to complexity.
What are the alternatives to Laravel Adjacency List, and when should I consider them?
Alternatives include **Materialized Path** (simpler queries but slower writes) and **Nested Set** (fast reads but complex updates). Use Adjacency List when reads are performance-critical and writes are infrequent. For write-heavy apps, Materialized Path may be better. Nested Set is rarely recommended due to update complexity. Adjacency List strikes a balance for most hierarchical data.
How do I test recursive relationships in my Laravel application, including edge cases like orphaned nodes?
Use Laravel’s testing tools to assert hierarchical data. For example, `assertDatabaseHas('categories', ['id' => 1])->descendants()->count()` verifies descendants. Test edge cases like orphaned nodes with `create()` and `delete()` operations, then assert relationships. The package includes static analysis (PHPStan) and CI tests, so your tests should mirror these patterns for consistency.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai