### Example JSON output of toTree() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Example JSON structure produced by `toTree()`, showing nested `children` arrays. ```json [ { "id": 1, "children": [ { "id": 2, "children": [ { "id": 3, "children": [] } ] }, { "id": 4, "children": [ { "id": 5, "children": [] } ] } ] } ] ``` -------------------------------- ### Enable Cycle Detection with Cycle Start and is_cycle Column Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Add includeCycleStart() to also retrieve the start of a cycle. Query results then include an is_cycle column indicating whether each node is part of a cycle. The example shows iterating over descendants and dumping is_cycle. ```php class User extends Model { public function enableCycleDetection(): bool { return true; } public function includeCycleStart(): bool { return true; } } $users = User::find($id)->descendants; foreach ($users as $user) { dump($user->is_cycle); } ``` -------------------------------- ### getModels() usage example Source: https://github.com/staudenmeir/laravel-adjacency-list Example of using tree() to get models with path column converted to the configured separator on all supported databases. ```php $users = User::tree()->get(); // each $user->path is "1.2.3" on every supported database ``` -------------------------------- ### Full cycle detection configuration example Source: https://github.com/staudenmeir/laravel-adjacency-list Complete model configuration enabling cycle detection and including cycle start, with a custom column name. The example then iterates descendants and checks the is_cycle flag to identify the first duplicate node of a cycle. ```php class TreeUser extends Model { use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships; public function enableCycleDetection(): bool { return true; } public function includeCycleStart(): bool { return true; // flag rather than drop cycle-closing rows } public function getCycleDetectionColumnName(): string { return 'is_cycle'; // default, overridden for illustration } } $descendants = TreeUser::find($id)->descendants; foreach ($descendants as $user) { if ($user->is_cycle) { // this row is the first duplicate node of a cycle } } ``` -------------------------------- ### includeCycleStart() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md When cycle detection is enabled, this method includes the start of a cycle (the first duplicate node) in query results. Override this method to return true to add an `is_cycle` column to results. ```APIDOC ## includeCycleStart() ### Description When cycle detection is enabled, this method includes the start of a cycle (the first duplicate node) in query results. Override this method to return true to add an `is_cycle` column to results. ### Method Method (PHP) ### Signature `public function includeCycleStart(): bool` ### Parameters None ### Return Value - **bool** - Returns `true` to include cycle start, `false` otherwise. ### Example ```php class User extends Model { public function enableCycleDetection(): bool { return true; } public function includeCycleStart(): bool { return true; } } $users = User::find($id)->descendants; foreach ($users as $user) { dump($user->is_cycle); } ``` ``` -------------------------------- ### Use tree() query scope Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Get all models beginning at the root(s) using the tree() query scope. ```php $tree = User::tree()->get(); ``` -------------------------------- ### Install with Composer (standard) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Install the package using Composer. Requires PHP and a supported database (MySQL 8.0+, MariaDB 10.2+, PostgreSQL 9.4+, SQLite 3.8.3+, SQL Server 2008+, or SingleStore 8.1+ for trees only). ```bash composer require staudenmeir/laravel-adjacency-list:"^1.0" ``` -------------------------------- ### Order Graph Queries Breadth-First or Depth-First Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use breadthFirst() to get siblings before children, or depthFirst() to get children before siblings. These scopes can be chained on descendant queries. ```php $descendants = Node::find($id)->descendants()->breadthFirst()->get(); $descendants = Node::find($id)->descendants()->depthFirst()->get(); ``` -------------------------------- ### getExpressionGrammar() usage example Source: https://github.com/staudenmeir/laravel-adjacency-list Example of compiling an ORDER BY path expression using the grammar. ```php $sql = $query->getExpressionGrammar()->compileOrderByPath(); ``` -------------------------------- ### Include Cycle Start in Results Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Override includeCycleStart() to return true to add an is_cycle column to query results, indicating whether a node is part of a cycle. Requires enableCycleDetection() to be true. ```php class Node extends Model { public function enableCycleDetection(): bool { return true; } public function includeCycleStart(): bool { return true; } } $nodes = Node::find($id)->descendants; foreach ($nodes as $node) { dump($node->is_cycle); } ``` -------------------------------- ### Install with Composer (PowerShell on Windows) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use this command when running in PowerShell on Windows (e.g., in VS Code) to avoid escaping issues with the caret character. ```powershell composer require staudenmeir/laravel-adjacency-list:"^^^^1.0" ``` -------------------------------- ### breadthFirst() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Query scope to order models breadth-first, getting siblings before children. Use it on tree, descendants, and similar queries. ```APIDOC ## breadthFirst() ### Description Orders the query results breadth-first, meaning siblings are returned before children. ### Usage ```php $tree = User::tree()->breadthFirst()->get(); ``` ``` -------------------------------- ### Use graph relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Examples of using the provided graph relationships: ancestors, descendants, children, parents, and their variants. Includes counting, updating, and deleting related nodes. ```php $ancestors = Node::find($id)->ancestors; $nodes = Node::with('descendants')->get(); $nodes = Node::has('children')->get(); $total = Node::find($id)->descendants()->count(); Node::find($id)->descendants()->update(['active' => false]); Node::find($id)->parents()->delete(); ``` -------------------------------- ### HasMany relationship between User and Post Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Base relationship used as a starting point for defining recursive relationships. ```php class User extends Model { public function posts() { return $this->hasMany(Post::class); } } ``` -------------------------------- ### Use included relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Examples of using the provided relationships: ancestors, descendants, siblings, and more. Includes querying, counting, updating, and deleting related models. ```php $ancestors = User::find($id)->ancestors; $users = User::with('descendants')->get(); $users = User::whereHas('siblings', function ($query) { $query->where('name', 'John'); })->get(); $total = User::find($id)->descendants()->count(); User::find($id)->descendants()->update(['active' => false]); User::find($id)->siblings()->delete(); ``` -------------------------------- ### depthFirst() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Query scope to order models depth-first, getting children before siblings. Use it on tree, descendants, and similar queries. ```APIDOC ## depthFirst() ### Description Orders the query results depth-first, meaning children are returned before siblings. ### Usage ```php $descendants = User::find($id)->descendants()->depthFirst()->get(); ``` ``` -------------------------------- ### Include cycle start with includeCycleStart() Source: https://github.com/staudenmeir/laravel-adjacency-list Override both enableCycleDetection() and includeCycleStart() to return true. When includeCycleStart() is true, the first duplicate node (cycle start) is included and flagged via an is_cycle column. Default is false, which excludes rows that close a cycle. ```php class User extends Model { public function enableCycleDetection(): bool { return true; } public function includeCycleStart(): bool { return true; } } ``` -------------------------------- ### breadthFirst() and depthFirst() usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Shows applying breadth-first and depth-first ordering to tree and descendant queries. ```php $tree = User::tree()->breadthFirst()->get(); $descendants = User::find($id)->descendants()->depthFirst()->get(); ``` -------------------------------- ### Accessing rootAncestor and rootAncestorOrSelf relations Source: https://github.com/staudenmeir/laravel-adjacency-list Usage examples for RootAncestor and RootAncestorOrSelf. rootAncestor returns the topmost parent or null; rootAncestorOrSelf returns the topmost parent or the model itself when no parent exists. ```php $root = User::find($id)->rootAncestor; // topmost parent (HasOne) — or null $root = User::find($id)->rootAncestorOrSelf; // topmost parent, else the model itself ``` -------------------------------- ### MorphToManyOfDescendantsAndSelf relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get all tags of a user and its descendants. Includes usage examples with find and withCount. ```php class User extends Model { public function recursiveTags() { return $this->morphToManyOfDescendantsAndSelf(Tag::class, 'taggable'); } } $recursiveTags = User::find($id)->recursiveTags; $users = User::withCount('recursiveTags')->get(); ``` -------------------------------- ### Adding custom constraints with withQueryConstraint() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use `withQueryConstraint()` to add custom constraints to the CTE's initial and recursive query. Example skips inactive users and their descendants. ```php $tree = User::withQueryConstraint(function (Builder $query) { $query->where('users.active', true); }, function () { return User::tree()->get(); }); ``` -------------------------------- ### HasManyOfDescendantsAndSelf relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get all posts of a user and its descendants. Includes usage examples with find and withCount. ```php class User extends Model { public function recursivePosts() { return $this->hasManyOfDescendantsAndSelf(Post::class); } } $recursivePosts = User::find($id)->recursivePosts; $users = User::withCount('recursivePosts')->get(); ``` -------------------------------- ### Accessing the bloodline relation Source: https://github.com/staudenmeir/laravel-adjacency-list Usage example for the bloodline relation. Returns ancestors, the model itself, and descendants in one CTE. ```php $bloodline = User::find($id)->bloodline; // ancestors, the model, and descendants in one CTE ``` -------------------------------- ### Enable Cycle Detection Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Override enableCycleDetection() to return true to prevent infinite loops when the graph contains cycles. ```php class Node extends Model { public function enableCycleDetection(): bool { return true; } } ``` -------------------------------- ### Ordering with breadthFirst() and depthFirst() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use these query scopes to order results breadth-first (siblings before children) or depth-first (children before siblings). ```php $tree = User::tree()->breadthFirst()->get(); $descendants = User::find($id)->descendants()->depthFirst()->get(); ``` -------------------------------- ### MorphToMany relationship between User and Tag Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Base relationship used as a starting point for defining recursive relationships. ```php class User extends Model { public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } } ``` -------------------------------- ### Check Relationships Between Models Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use isChildOf(), isParentOf(), and getDepthRelatedTo() to check relationships. The example creates a hierarchy and shows outputs: isChildOf returns true, isParentOf returns true, getDepthRelatedTo returns 2. ```php $rootUser = User::create(['parent_id' => null]); $firstLevelUser = User::create(['parent_id' => $rootUser->id]); $secondLevelUser = User::create(['parent_id' => $firstLevelUser->id]); $isChildOf = $secondLevelUser->isChildOf($firstLevelUser); // Output: true $isParentOf = $rootUser->isParentOf($firstLevelUser); // Output: true $depthRelatedTo = $secondLevelUser->getDepthRelatedTo($rootUser); // Output: 2 ``` -------------------------------- ### MorphToManyOfDescendants relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get only the descendants' tags. ```php class User extends Model { public function descendantTags() { return $this->morphToManyOfDescendants(Tag::class, 'taggable'); } } ``` -------------------------------- ### MorphedByMany relationship between Category and Post Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Base relationship used as a starting point for defining recursive relationships. ```php class Category extends Model { public function posts() { return $this->morphedByMany(Post::class, 'categorizable'); } } ``` -------------------------------- ### toTree() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Method on a result collection to generate a nested tree by recursively setting 'children' relationships. ```APIDOC ## toTree() ### Description Generates a nested tree from a collection of models by recursively setting 'children' relationships. ### Usage ```php $users = User::tree()->get(); $tree = $users->toTree(); ``` ### Response Example ```json [ { "id": 1, "children": [ { "id": 2, "children": [ { "id": 3, "children": [] } ] }, { "id": 4, "children": [ { "id": 5, "children": [] } ] } ] } ] ``` ``` -------------------------------- ### Generate IDE Helper Models for a User Model Source: https://github.com/staudenmeir/laravel-adjacency-list Run this artisan command to generate IDE helper annotations for a specific model. The command is available when the barryvdh/laravel-ide-helper package is installed (dev/suggested dependency). ```bash php artisan ide-helper:models "App\Models\User" ``` -------------------------------- ### BelongsToMany relationship between User and Role Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Base relationship used as a starting point for defining recursive relationships. ```php class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } } ``` -------------------------------- ### HasManyOfDescendants relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get only the descendants' posts. ```php class User extends Model { public function descendantPosts() { return $this->hasManyOfDescendants(Post::class); } } ``` -------------------------------- ### Use loadTreeRelationships() with toTree() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Load tree relationships and convert the collection to a tree structure using toTree(). ```php $users = User::tree(1)->get(); $tree = $users->loadTreeRelationships()->toTree(); ``` -------------------------------- ### tree() and treeOf() usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Shows how to call tree() and treeOf() with optional max depth, a closure constraint, and a model instance as root. ```php $tree = User::tree()->get(); // whole tree, root(s) first $tree = User::tree(3)->get(); // maximum depth 3 $constraint = fn ($query) => $query->whereNull('parent_id')->where('list_id', 1); $tree = User::treeOf($constraint)->get(); $tree = User::treeOf($constraint, 3)->get(); // A model instance can be used as the root constraint directly $tree = User::treeOf(User::find(1))->get(); ``` -------------------------------- ### Filter scopes usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Shows usage of the filter scopes. isLeaf() is equivalent to doesntHaveChildren(). ```php $leaves = User::isLeaf()->get(); // same as doesntHaveChildren() $roots = User::isRoot()->get(); $noRoots = User::hasParent()->get(); $noLeaves = User::hasChildren()->get(); ``` -------------------------------- ### Get Subgraph with Maximum Depth Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Pass a maximum depth as the second argument to subgraph() to limit the depth of the subgraph. ```php $subgraph = Node::subgraph($constraint, 3)->get(); ``` -------------------------------- ### Add custom constraints to CTE initial and recursive queries Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Uses withQueryConstraint() to add a constraint to both the initial and recursive queries of the CTE. The example filters for active nodes, skipping inactive nodes and their descendants. ```php $descendants = Node::withQueryConstraint(function (Builder $query) { $query->where('nodes.active', true); }, function () { return Node::find($id)->descendants; }); ``` -------------------------------- ### Catch RuntimeException for deep relationship with recursive relation not first Source: https://github.com/staudenmeir/laravel-adjacency-list Constructing a deep relationship where the recursive relation is not at the start throws a RuntimeException with the message 'Descendants can only be at the beginning of deep relationships at the moment.' This example shows the failing chain and how to catch it. ```php // Deep relationship constructed with the recursive relation at the start works: $posts = User::find($id)->descendantPosts; try { // Constructing a chain where the recursive relation is NOT first: $this->hasManyDeepFromRelations( (new Post())->belongsTo(User::class), // position 0 (new User())->descendants() // position 1 -> RuntimeException ); } catch (RuntimeException $e) { // "Descendants can only be at the beginning of deep relationships at the moment." } ``` -------------------------------- ### whereDepth() usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Shows filtering descendants by exact depth or comparison operator. ```php $descendants = User::find($id)->descendants()->whereDepth(2)->get(); $descendants = User::find($id)->descendants()->whereDepth('<', 3)->get(); ``` -------------------------------- ### Intermediate scopes for recursive relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to adjust the descendants query using withTrashedDescendants, withIntermediateScope, and withoutIntermediateScope. ```php User::find($id)->recursivePosts()->withTrashedDescendants()->get(); User::find($id)->recursivePosts()->withIntermediateScope('active', new ActiveScope())->get(); User::find($id)->recursivePosts()->withIntermediateScope( 'depth', function ($query) { $query->whereDepth('<=', 10); } )->get(); User::find($id)->recursivePosts()->withoutIntermediateScope('active')->get(); ``` -------------------------------- ### withMaxDepth() usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Shows using withMaxDepth() to limit descendant and ancestor queries by absolute depth. ```php $descendants = User::withMaxDepth(3, function () use ($id) { return User::find($id)->descendants; }); $ancestors = User::withMaxDepth(-3, function () use ($id) { return User::find($id)->ancestors; }); ``` -------------------------------- ### Accessing siblings and siblingsAndSelf relations Source: https://github.com/staudenmeir/laravel-adjacency-list Usage examples for the Siblings relation. siblings returns the parent's other children; siblingsAndSelf returns every child of the parent including the model itself. ```php $siblings = User::find($id)->siblings; // the parent's other children $allChildren = User::find($id)->siblingsAndSelf; // every child of the parent including this model ``` -------------------------------- ### withQueryConstraint example Source: https://github.com/staudenmeir/laravel-adjacency-list Applies the same constraint to both initial and recursive branches. Saves and restores previous values of both static properties, so nested calls behave correctly. ```php $descendants = Node::withQueryConstraint( function (Builder $query) { $query->where('nodes.active', true); }, function () use ($id) { return Node::find($id)->descendants; } ); ``` -------------------------------- ### Usage example for morphToManyOfDescendants and morphToManyOfDescendantsAndSelf Source: https://github.com/staudenmeir/laravel-adjacency-list Example model methods using morphToManyOfDescendantsAndSelf and morphToManyOfDescendants to define recursive and descendant tag relations. Shows retrieval with find and withCount. ```php class User extends Model { public function recursiveTags() { return $this->morphToManyOfDescendantsAndSelf(Tag::class, 'taggable'); } public function descendantTags() { return $this->morphToManyOfDescendants(Tag::class, 'taggable'); } } $recursiveTags = User::find($id)->recursiveTags; $users = User::withCount('recursiveTags')->get(); ``` -------------------------------- ### Customizing path separator with getPathSeparator() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Override this method to customize the path separator used in the `path` column. ```php class User extends Model { public function getPathSeparator() { return '.'; } } ``` -------------------------------- ### getQuery() return type example Source: https://github.com/staudenmeir/laravel-adjacency-list Shows the return type of getQuery() as Staudenmeir\LaravelCte\Query\Builder, which is required for withRecursiveExpression() to be available. ```php /** @var \Staudenmeir\LaravelAdjacencyList\Eloquent\Builder $builder */ $baseQuery = $builder->getQuery(); // Staudenmeir\LaravelCte\Query\Builder ``` -------------------------------- ### Create nodes and edges tables for graph relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Schema for storing directed graphs as nodes and edges. The edges table has source_id, target_id, label, and weight columns. ```php Schema::create('nodes', function (Blueprint $table) { $table->id(); }); Schema::create('edges', function (Blueprint $table) { $table->unsignedBigInteger('source_id'); $table->unsignedBigInteger('target_id'); $table->string('label'); $table->unsignedBigInteger('weight'); }); ``` -------------------------------- ### Enable Cycle Detection in Model Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Override enableCycleDetection() in your model to return true when your tree contains cycles, preventing infinite loops during traversal. ```php class User extends Model { public function enableCycleDetection(): bool { return true; } } ``` -------------------------------- ### Build tree from full tree query with User::tree()->get() Source: https://github.com/staudenmeir/laravel-adjacency-list Shows how to convert a flat collection from a tree query into a nested tree structure. The result JSON shape is provided as a comment. ```php $users = User::tree()->get(); $tree = $users->toTree(); // Result JSON shape: // [{"id":1,"children":[{"id":2,"children":[{"id":3,"children":[]}]},{"id":4,"children":[{"id":5,"children":[]}]}]}] ``` -------------------------------- ### Usage example for morphedByManyOfDescendants and morphedByManyOfDescendantsAndSelf Source: https://github.com/staudenmeir/laravel-adjacency-list Example model methods using morphedByManyOfDescendantsAndSelf and morphedByManyOfDescendants to define recursive and descendant post relations. Shows retrieval with find and withCount. ```php class Category extends Model { public function recursivePosts() { return $this->morphedByManyOfDescendantsAndSelf(Post::class, 'categorizable'); } public function descendantPosts() { return $this->morphedByManyOfDescendants(Post::class, 'categorizable'); } } $recursivePosts = Category::find($id)->recursivePosts; $categories = Category::withCount('recursivePosts')->get(); ``` -------------------------------- ### Reversing custom paths with 'reverse' option Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Set `'reverse' => true` in a custom path definition to reverse the path order. ```php class User extends Model { public function getCustomPaths() { return [ [ 'name' => 'reverse_slug_path', 'column' => 'slug', 'separator' => '/', 'reverse' => true, ], ]; } } ``` -------------------------------- ### Customize Path Separator Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Override getPathSeparator() to change the separator used in the path column. ```php class Node extends Model { public function getPathSeparator(): string { return '.'; } } ``` -------------------------------- ### Filter models by tree position Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Query scopes to filter models: hasChildren(), hasParent(), isLeaf(), doesntHaveChildren(), and isRoot(). ```php $noLeaves = User::hasChildren()->get(); $noRoots = User::hasParent()->get(); $leaves = User::isLeaf()->get(); $leaves = User::doesntHaveChildren()->get(); $roots = User::isRoot()->get(); ``` -------------------------------- ### Catch RuntimeException for withCount('descendants') on MariaDB Source: https://github.com/staudenmeir/laravel-adjacency-list All failures from the package arrive as \RuntimeException, so no package-specific error classes are needed. This example catches the exception when using withCount('descendants') on MariaDB, where correlated CTEs in subqueries are not supported (MDEV-19077). ```php use Illuminate\Database\Eloquent\Builder; use RuntimeException; try { $users = User::withCount('descendants')->get(); } catch (RuntimeException $e) { // MariaDB: correlated CTE in subquery not supported by the database // (or any of the four conditions above) report($e); } ``` -------------------------------- ### enableCycleDetection() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Enables cycle detection on the model to prevent infinite loops when traversing cyclic trees. Override this method in your Eloquent model to return true. ```APIDOC ## enableCycleDetection() ### Description Enables cycle detection on the model to prevent infinite loops when traversing cyclic trees. Override this method in your Eloquent model to return true. ### Method Method (PHP) ### Signature `public function enableCycleDetection(): bool` ### Parameters None ### Return Value - **bool** - Returns `true` to enable cycle detection, `false` otherwise. ### Example ```php class User extends Model { public function enableCycleDetection(): bool { return true; } } ``` ``` -------------------------------- ### Adding custom path columns with getCustomPaths() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Define custom path columns in `getCustomPaths()` to add them to query results. Each entry specifies a name, column, and separator. ```php class User extends Model { public function getCustomPaths() { return [ [ 'name' => 'slug_path', 'column' => 'slug', 'separator' => '/', ], ]; } } $descendantsAndSelf = User::find(1)->descendantsAndSelf; echo $descendantsAndSelf[0]->slug_path; // user-1 echo $descendantsAndSelf[1]->slug_path; // user-1/user-2 echo $descendantsAndSelf[2]->slug_path; // user-1/user-2/user-3 ``` -------------------------------- ### getPivotColumns() example with pivot attributes Source: https://github.com/staudenmeir/laravel-adjacency-list Override getPivotColumns() to return extra pivot columns. The columns are selected for each recursive result and exposed as pivot_{column} attributes or a pivot relation after materialization. The example dumps pivot->label and pivot->weight for each descendant. ```php class Node extends Model { public function getPivotColumns(): array { return ['label', 'weight']; } } $nodes = Node::find($id)->descendants; foreach ($nodes as $node) { dump($node->pivot->label, $node->pivot->weight); } ``` -------------------------------- ### Override getParentKeyName() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Customize the parent key name by overriding getParentKeyName(). Default is 'parent_id'. ```php class User extends Model { public function getParentKeyName() { return 'parent_id'; } } ``` -------------------------------- ### MorphedByManyOfDescendantsAndSelf relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get all posts of a category and its descendants. Includes usage examples with find and withCount. ```php class Category extends Model { public function recursivePosts() { return $this->morphedByManyOfDescendantsAndSelf(Post::class, 'categorizable'); } } $recursivePosts = Category::find($id)->recursivePosts; $categories = Category::withCount('recursivePosts')->get(); ``` -------------------------------- ### Generated PHPDoc Annotations for Recursive Relationships Source: https://github.com/staudenmeir/laravel-adjacency-list Example output for a model using HasRecursiveRelationships. Shows the generated @property-read annotations for recursive children, depth, path, and relation count. The generics syntax (Collection) is used when ide-helper.use_generics_annotations is true (default). ```php /** * @property-read \Staudenmeir\LaravelAdjacencyList\Eloquent\Collection $descendants The model's recursive children. * @property-read int|null $depth * @property-read string|null $path * @property-read int|null $descendants_count */ class User extends Model { // ... } ``` -------------------------------- ### BelongsToManyOfDescendantsAndSelf relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get all roles of a user and its descendants. Includes usage examples with find and withCount. ```php class User extends Model { public function recursiveRoles() { return $this->belongsToManyOfDescendantsAndSelf(Role::class); } } $recursiveRoles = User::find($id)->recursiveRoles; $users = User::withCount('recursiveRoles')->get(); ``` -------------------------------- ### getModels() method signature Source: https://github.com/staudenmeir/laravel-adjacency-list Overrides the base getModels() used by get() and paginate(). Fetches hydrated rows from the CTE and handles PostgreSQL path conversion. ```php public function getModels($columns = ['*']) ``` -------------------------------- ### Generating nested tree with toTree() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Call `toTree()` on a result collection to generate a nested tree, recursively setting `children` relationships. ```php $users = User::tree()->get(); $tree = $users->toTree(); ``` -------------------------------- ### Optimize Depth-Limited Queries with withMaxDepth Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use withMaxDepth() to set a maximum depth that improves performance by only building the requested section of the graph. Works with negative depths for ancestors. ```php $descendants = Node::withMaxDepth(3, function () use ($id) { return Node::find($id)->descendants; }); ``` ```php $ancestors = Node::withMaxDepth(-3, function () use ($id) { return Node::find($id)->ancestors; }); ``` -------------------------------- ### Create users table with parent_id column Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Schema definition for hierarchical data in trees, with a nullable parent_id column for the recursive relationship. ```php Schema::create('users', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('parent_id')->nullable(); }); ``` -------------------------------- ### Filtering by depth with whereDepth() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use `whereDepth()` to filter models by relative depth. Supports equality or comparison operators. ```php $descendants = User::find($id)->descendants()->whereDepth(2)->get(); $descendants = User::find($id)->descendants()->whereDepth('<', 3)->get(); ``` -------------------------------- ### Dynamic write methods on recursive relations Source: https://github.com/staudenmeir/laravel-adjacency-list Shows how to perform update, delete, and increment operations on recursive relations. The update and increment calls target the real table instead of the CTE view, while the delete example uses siblings() which overrides getResults() but is not a CTE relation. ```php User::find($id)->descendants()->update(['active' => false]); ``` ```php User::find($id)->siblings()->delete(); // Siblings overrides getResults() but is not a CTE relation ``` ```php User::find($id)->descendants()->increment('count'); ``` -------------------------------- ### withMaxDepth() usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Usage of withMaxDepth for descendants and ancestors. Positive depth for descendants, negative for ancestors. ```php $descendants = Node::withMaxDepth(3, function () use ($id) { return Node::find($id)->descendants; }); $ancestors = Node::withMaxDepth(-3, function () use ($id) { return Node::find($id)->ancestors; }); ``` -------------------------------- ### Query graph relationships Source: https://github.com/staudenmeir/laravel-adjacency-list Examples of querying graph relationships: accessing ancestors, eager loading descendants, counting descendants, updating descendants, and deleting parents. ```php $ancestors = Node::find($id)->ancestors; $nodes = Node::with('descendants')->get(); $total = Node::find($id)->descendants()->count(); Node::find($id)->descendants()->update(['active' => false]); Node::find($id)->parents()->delete(); ``` -------------------------------- ### withRecursiveQueryConstraint example Source: https://github.com/staudenmeir/laravel-adjacency-list Applies a constraint to the CTE's recursive branch only. Typically used to skip subtrees. ```php $tree = User::withRecursiveQueryConstraint( function (Builder $query) { $query->where('users.active', true); }, function () { return User::tree()->get(); } ); ``` -------------------------------- ### whereDepth(), breadthFirst(), depthFirst() usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Usage of the three scopes on descendant queries. whereDepth filters by depth, breadthFirst and depthFirst control traversal order. ```php $descendants = Node::find($id)->descendants()->whereDepth(2)->get(); $descendants = Node::find($id)->descendants()->whereDepth('<', 3)->get(); $descendants = Node::find($id)->descendants()->breadthFirst()->get(); $descendants = Node::find($id)->descendants()->depthFirst()->get(); ``` -------------------------------- ### Pass maximum depth to tree() and treeOf() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Limit the tree depth by passing an integer as the first argument to tree() or as the second argument to treeOf(). ```php $tree = User::tree(3)->get(); $tree = User::treeOf($constraint, 3)->get(); ``` -------------------------------- ### Load tree relationships with loadTreeRelationships() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Chaperone tree relationships to load ancestors and parent relationships already present in the tree, potentially reducing N+1 queries. ```php $users = User::tree(3)->get(); $users->loadTreeRelationships(); ``` -------------------------------- ### Access Path in Query Results Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Ancestor, descendant, and subgraph queries include a path column with dot-separated local keys from the query's parent to the node. ```php $descendantsAndSelf = Node::find(1)->descendantsAndSelf()->depthFirst()->get(); echo $descendantsAndSelf[0]->path; // 1 echo $descendantsAndSelf[1]->path; // 1.2 echo $descendantsAndSelf[2]->path; // 1.2.3 ``` -------------------------------- ### Use treeOf() with custom constraints Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Query trees with custom constraints for root models, e.g., filtering by list_id. The constraint closure is passed to treeOf(). ```php $constraint = function ($query) { $query->whereNull('parent_id')->where('list_id', 1); }; $tree = User::treeOf($constraint)->get(); ``` -------------------------------- ### MorphedByManyOfDescendants relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get only the descendants' posts. ```php class Category extends Model { public function descendantPosts() { return $this->morphedByManyOfDescendants(Post::class, 'categorizable'); } } ``` -------------------------------- ### withInitialQueryConstraint example Source: https://github.com/staudenmeir/laravel-adjacency-list Applies a constraint to the CTE's initial query only. The closure receives an Eloquent\Builder and is applied to the initial query. The second closure's return value is returned. ```php $tree = User::withInitialQueryConstraint( function (Builder $query) { $query->where('users.list_id', 1); }, function () { return User::tree()->get(); } ); ``` -------------------------------- ### Override getLocalKeyName() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Customize the local key name by overriding getLocalKeyName(). Default is the model's primary key. ```php class User extends Model { public function getLocalKeyName() { return 'id'; } } ``` -------------------------------- ### Tree Variant Usage with HasManyDeep Source: https://github.com/staudenmeir/laravel-adjacency-list Shows how to define a deep relationship from descendants to posts using the tree variant. Requires the HasRelationships and HasRecursiveRelationships traits. The descendantPosts method returns a HasManyDeep instance, and the example retrieves descendant posts for a user. ```php use \Staudenmeir\EloquentHasManyDeep\HasRelationships; use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships; class User extends Model { use HasRelationships; use HasRecursiveRelationships; public function descendantPosts(): \Staudenmeir\EloquentHasManyDeep\HasManyDeep { return $this->hasManyDeepFromRelations( $this->descendants(), (new static)->posts() ); } public function posts() { return $this->hasMany(Post::class); } } $descendantPosts = User::find($id)->descendantPosts; ``` -------------------------------- ### subgraph() usage examples Source: https://github.com/staudenmeir/laravel-adjacency-list Calls subgraph() with and without max depth. The constraint seeds root nodes via whereIn. ```php $subgraph = Node::subgraph(fn ($query) => $query->whereIn('id', $ids))->get(); $subgraph = Node::subgraph(fn ($query) => $query->whereIn('id', $ids), 3)->get(); ``` -------------------------------- ### BelongsToManyOfDescendants relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a recursive relationship to get only the descendants' roles. ```php class User extends Model { public function descendantRoles() { return $this->belongsToManyOfDescendants(Role::class); } } ``` -------------------------------- ### Enable common table expressions outside Laravel Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Adds the QueriesExpressions trait to a model when using the package outside of Laravel or when package discovery is disabled. ```php class Post extends Model { use \Staudenmeir\LaravelCte\Eloquent\QueriesExpressions; } ``` -------------------------------- ### Using isChildOf, isParentOf, and getDepthRelatedTo Source: https://github.com/staudenmeir/laravel-adjacency-list Shows how to use the helper methods to check parent-child relationships and depth differences. The example creates a three-level hierarchy and demonstrates that isChildOf returns true for direct parent, isParentOf returns true for direct children, and getDepthRelatedTo returns the depth difference. Models not in the same tree return null. ```php $rootUser = User::create(['parent_id' => null]); $firstLevelUser = User::create(['parent_id' => $rootUser->id]); $secondLevelUser = User::create(['parent_id' => $firstLevelUser->id]); $secondLevelUser->isChildOf($firstLevelUser); // true $rootUser->isParentOf($firstLevelUser); // true $secondLevelUser->getDepthRelatedTo($rootUser); // 2 // Models not in the same tree return null $secondLevelUser->getDepthRelatedTo(UnrelatedUser::find(1)); // null ``` -------------------------------- ### Retrieve Pivot Columns in Graph Relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Override getPivotColumns() to include additional columns from the pivot table in graph queries. Access them via $node->pivot->columnName. ```php class Node extends Model { public function getPivotColumns(): array { return ['label', 'weight']; } } $nodes = Node::find($id)->descendants; foreach ($nodes as $node) { dump( $node->pivot->label, $node->pivot->weight ); } ``` -------------------------------- ### setRecursiveQueryConstraint and unsetRecursiveQueryConstraint example Source: https://github.com/staudenmeir/laravel-adjacency-list Persistently registers a recursive constraint without automatic restore. Use with caution; prefer the with* methods. The constraint remains active until unset. ```php User::setRecursiveQueryConstraint(fn (Builder $query) => $query->where('users.active', true)); // ...all subsequent recursive query builds use the constraint... User::unsetRecursiveQueryConstraint(); ``` -------------------------------- ### Limiting depth with withMaxDepth() for performance Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use `withMaxDepth()` to set a maximum depth that improves query performance by only building the requested section of the tree. Works with negative depths (technically a minimum). ```php $descendants = User::withMaxDepth(3, function () use ($id) { return User::find($id)->descendants; }); ``` ```php $ancestors = User::withMaxDepth(-3, function () use ($id) { return User::find($id)->ancestors; }); ``` -------------------------------- ### Customize parent and child key names Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Override getParentKeyName and getChildKeyName to customize the pivot table column names. By default, the trait expects parent_id and child_id. ```php class Node extends Model { public function getParentKeyName(): string { return 'source_id'; } public function getChildKeyName(): string { return 'target_id'; } } ``` -------------------------------- ### Generate nested tree with toTree() Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Converts a result collection into a nested tree structure using the toTree() method. The method recursively sets 'children' relationships on each node. ```php $nodes = Node::find($id)->descendants; $tree = $nodes->toTree(); ``` -------------------------------- ### Unsupported database driver throws RuntimeException Source: https://github.com/staudenmeir/laravel-adjacency-list Thrown when a query uses the package traits on a connection with an unsupported driver. The dispatch is a match on the driver name in getExpressionGrammar(), and the default arm throws this exception. ```php default => throw new RuntimeException('This database is not supported.'), ``` -------------------------------- ### Access is_cycle column in query results Source: https://github.com/staudenmeir/laravel-adjacency-list When includeCycleStart() is true, the boolean column named by getCycleDetectionColumnName() (default 'is_cycle') is added to query results. This example dumps the is_cycle value for each descendant. ```php $users = User::find($id)->descendants; foreach ($users as $user) { dump($user->is_cycle); } ``` -------------------------------- ### Query ancestors, ancestorsAndSelf, and existence check Source: https://github.com/staudenmeir/laravel-adjacency-list Shows usage of the Ancestors relation: $user->ancestors retrieves recursive parents, $user->ancestorsAndSelf includes the user itself, and $user->ancestors()->exists() checks if the user has a parent. ```php $ancestors = $user->ancestors; // recursive parents $chain = $user->ancestorsAndSelf; // includes the user itself $hasParent = $user->ancestors()->exists(); ``` -------------------------------- ### getCustomPaths() Source: https://github.com/staudenmeir/laravel-adjacency-list Returns an array of custom path definitions. Override to add extra path columns. ```APIDOC ## getCustomPaths() ### Description Returns an array of custom path definitions. Override to add extra path columns. ### Method public function getCustomPaths() ### Returns - **array** - Default: `[]` - Each entry: `array{name: string, column: string|\Illuminate\Contracts\Database\Query\Expression, separator: string, reverse?: bool}` ``` -------------------------------- ### Get Subgraph with Custom Constraint Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Use the subgraph() query scope to retrieve a subgraph based on a custom constraint. The constraint is a closure that modifies the query. ```php $constraint = function ($query) { $query->whereIn('id', $ids); }; $subgraph = Node::subgraph($constraint)->get(); ``` -------------------------------- ### Constructor signature for IsRecursiveRelation Source: https://github.com/staudenmeir/laravel-adjacency-list Defines the constructor used by Ancestors and Descendants relations; RootAncestor reuses it via baseConstruct. Parameters include the related query builder, owning model, qualified parent key column, local key column, and an inclusion flag for the parent model. ```php public function __construct(Builder $query, Model $parent, $foreignKey, $localKey, $andSelf) ``` -------------------------------- ### Register IdeHelperServiceProvider via composer.json extra Source: https://github.com/staudenmeir/laravel-adjacency-list Adds the package's optional Laravel service provider through Composer's package-discovery extra key so it is auto-discovered. Required for the IDE helper integration to work. ```json "extra": { "laravel": { "providers": [ "Staudenmeir\LaravelAdjacencyList\IdeHelperServiceProvider" ] } } ``` -------------------------------- ### getExpressionGrammar() method signature Source: https://github.com/staudenmeir/laravel-adjacency-list Returns the database-specific ExpressionGrammar implementation for the connection's driver. ```php public function getExpressionGrammar() ``` -------------------------------- ### breadthFirst() and depthFirst() scope signatures Source: https://github.com/staudenmeir/laravel-adjacency-list Declares the breadthFirst() and depthFirst() scopes. breadthFirst() orders by depth; depthFirst() uses compiled path ordering. ```php public function scopeBreadthFirst(Builder $query) // orderBy(depth) public function scopeDepthFirst(Builder $query) // orderByRaw(compiled path ordering) ``` -------------------------------- ### isParentOf(Model $model) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Checks if the current model is a parent of the given model. Returns a boolean indicating the relationship. ```APIDOC ## isParentOf(Model $model) ### Description Checks if the current model is a parent of the given model. Returns a boolean indicating the relationship. ### Method Method (PHP) ### Signature `isParentOf(Model $model)` ### Parameters - **$model** (Model) - Required - The model to check against. ### Return Value - **bool** - Returns `true` if the current model is a parent of the given model, `false` otherwise. ### Example ```php $isParentOf = $rootUser->isParentOf($firstLevelUser); // Output: true ``` ```