twocoffeecups / lara-adjacency-list
Lite adjacency list for laravel.
Requires
- php: ^8.0
This package is auto-updated.
Last update: 2025-06-26 12:57:28 UTC
README
Simple plugin for working with a Adjacency List for laravel.
In dev.
Compatibility
Laravel 8.x + version.
Installation
Install package:
composer require twocoffeecups/lara-adjacency-list
Use the HasAdjacencyList trait in your model:
use TwoCoffeeCups\LaraAdjacencyList\AdjacencyList\HasAdjacencyList;
class YourModel extends Model
{
use HasAdjacencyList;
}
Add column in your table schema:
Schema::create('your_table_name', function (Blueprint $table) {
$table->id();
$table->foreignId('parentId')->nullable()->index('parentIdx')->constrained('your_table_name');
});
Or run this command if you already have a table in the database and enter table name:
php artisan adjacency-list:add-parent-id
Usage
Keys
If you already have a table with the parent and local keys, then you can redefine their names in the model:
use TwoCoffeeCups\LaraAdjacencyList\AdjacencyList\HasAdjacencyList;
class YourModel extends Model
{
use HasAdjacencyList;
public function getLocalIdName(): string
{
return 'your_local_id_name';
}
public function getParentIdName(): string
{
return 'your_parent_id_name';
}
}
Relationships
The trait has various relationships:
children()
Get only children nodes.parent()
Get parent node.allAncestors()
Get ancestors list.allAncestorsAndMe()
Get ancestors list, and self.allDescendants()
Get descendants list.allAncestorsAndMe()
Get ancestors list, and self.
Methods usage:
$node = Model::find($id);
$node->allAncestors();
Tree
The static method getTree()
allows you to get a tree of all elements starting from the roots:
$tree = Model::getTree();
Get method descendantsTree()
to create a tree of all descendants:
$tree = $model->descendantsTree()->get();
The static method onlyRoots()
allows you to get only the root elements:
$roots = Model::onlyRoots();