lara-hierarchial-collections
lara-hierarchial-collections copied to clipboard
Transform flat collection to a nested Hierarchy
Transforms flat collections to a nested hierarchy
Package to extend collections of hierarchical data to organize data into nodes according to the hierarchy.
The package supports unlimited starting nodes, and has been tested to 10 levels deep.
Use Cases:
- Organizational Charts
- Chart of Accounts
Requirements:
- Illuminate Collections 8+/9+/10+/11+ (Packaged in Laravel 8+/9+/10+/11+)
- PHP 8.0 / 8.1 / 8.2 / 8.3
Installation
You can install the package via composer:
composer require robertmarney/lara-hierarchial-collections
Basic Usage,
The tool accepts Support Collections or Eloquent Collections, within the collection we expect Eloquent Models or StdClass
objects.
Assuming a primary key of id
and parent identifier of parent_id
:
$laraHierarchy = new RCM\LaraHierarchy\LaraHierarchy();
$collection = User::select(['id', 'parent_id', 'name'])->get();
$hierarchy = $laraHierarchy->collectionToHierarchy($collection)->toArray();
// Result:
[
'id' => 1,
'parent_id' => null,
'name' => 'John Doe'
'children' => [
[
'id' => 1000,
'parent_id' => 1,
'name' => 'Sue Smith'
'children' => [//...]
],
//...
]
]
Customizing Local Key:
If you are not using ids (eg uuid) you can override the local comparison value:
$hierarchy = $laraHierarchy->collectionToHierarchy($collection, localIdentifier: 'custom_primary_key')
Customizing Parent Key:
Similiarly, you can change the parent key if the local relationship is not formed on the default parent_id
$hierarchy = $laraHierarchy->collectionToHierarchy($collection, parentIdentifier: 'custom_parent_id')
Providing the relationName
property will change the collection name where children will be placed
$hierarchy = $laraHierarchy->collectionToHierarchy($collection, relationName: 'descendants')->toArray();
// Result:
[
'id' => 1,
'parent_id' => null,
'name' => 'John Doe'
'descendants' => [
[
'id' => 1000,
'parent_id' => 1,
'name' => 'Sue Smith'
'descendants' => [//...]
],
//...
]
]
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
- Robert Marney
- All Contributors
License
The MIT License (MIT). Please see License File for more information.