jeffersonsimaogoncalves / lara-hierarchial-collections

Transform flat collection to a nested Hierarchy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Transforms flat collections to a nested hierarchy

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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+ (Packaged in Laravel 8+/9+)
  • PHP 8.0 / 8.1

Installation

You can install the package via composer:

composer require robertmarney/lara-hierarchial-collections

Basic Usage,

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

License

The MIT License (MIT). Please see License File for more information.

About

Transform flat collection to a nested Hierarchy

License:MIT License


Languages

Language:PHP 100.0%