PHPackages                             gzero/eloquent-tree - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. gzero/eloquent-tree

ActiveLibrary[Database &amp; ORM](/categories/database)

gzero/eloquent-tree
===================

Eloquent Tree is a tree model for Laravel Eloquent ORM.

v3.1.2(7y ago)13257.1k↓15.4%21[2 issues](https://github.com/AdrianSkierniewski/eloquent-tree/issues)2MITPHPPHP &gt;=5.6.0

Since Dec 22Pushed 7y ago8 watchersCompare

[ Source](https://github.com/AdrianSkierniewski/eloquent-tree)[ Packagist](https://packagist.org/packages/gzero/eloquent-tree)[ RSS](/packages/gzero-eloquent-tree/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (2)Versions (16)Used By (2)

eloquent-tree [![Latest Stable Version](https://camo.githubusercontent.com/c6f9e6347c5b53902b891e06ad168f130abee85ab0461ebcbc9408e7764c4c37/68747470733a2f2f706f7365722e707567782e6f72672f677a65726f2f656c6f7175656e742d747265652f762f737461626c652e706e67)](https://packagist.org/packages/gzero/eloquent-tree) [![Total Downloads](https://camo.githubusercontent.com/d97f0808069278cfeaee951a030eefd4686b2fe2a898a561d9ad10828d379fcf/68747470733a2f2f706f7365722e707567782e6f72672f677a65726f2f656c6f7175656e742d747265652f646f776e6c6f6164732e706e67)](https://packagist.org/packages/gzero/eloquent-tree) [![Build Status](https://camo.githubusercontent.com/020eb71e93c78ca1dd0c7f9779f6f346d75ba0a8119df12e6750289a7e7a0182/68747470733a2f2f7472617669732d63692e6f72672f41647269616e536b6965726e696577736b692f656c6f7175656e742d747265652e706e67)](https://travis-ci.org/AdrianSkierniewski/eloquent-tree)
===================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#eloquent-tree---)

Eloquent Tree is a tree model for Laravel Eloquent ORM.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Migration](#migration)
- [Example usage](#example-usage)
- [Events](#events)
- [Support](#support)

\##Features

- Creating root, children and sibling nodes
- Getting children
- Getting descendants
- Getting ancestor
- Moving sub-tree
- Building tree on PHP side

Installation
------------

[](#installation)

**Version 1.0 is not compatible with 0.**\*

**Version 2.0 - Laravel 5 support**

**Version 2.1 - Laravel 5.1 support**

**Version 3.0 - Laravel 5.3 support**

Begin by installing this package through Composer. Edit your project's composer.json file to require gzero/eloquent-tree.

```
"require": {
    "laravel/framework": "5.3.*",
    "gzero/eloquent-tree": "v3.0.*"
},
"minimum-stability" : "stable"
```

Next, update Composer from the Terminal:

```
composer update

```

That's all now you can extend \\Gzero\\EloquentTree\\Model\\Tree in your project

Migration
---------

[](#migration)

Simply migration with all required columns that you could extend by adding new fields

```
Schema::create(
    'trees',
    function (Blueprint $table) {
        $table->increments('id');
        $table->string('path', 255)->nullable();
        $table->integer('parent_id')->unsigned()->nullable();
        $table->integer('level')->default(0);
        $table->timestamps();
        $table->index(array('path', 'parent_id', 'level'));
        $table->foreign('parent_id')->references('id')->on('contents')->onDelete('CASCADE');
    }
);
```

Example usage
-------------

[](#example-usage)

- [Inserting and Updating new nodes](#inserting-and-updating-new-nodes)
- [Getting tree nodes](#getting-tree-nodes)
- [Finding Leaf nodes](#getting-leaf-nodes)
- [Map from array](#map-from-array)
- [Rendering tree](#rendering-tree)

### Inserting and updating new nodes

[](#inserting-and-updating-new-nodes)

```
$root       = new Tree(); // New root
$root->setAsRoot();
$child      = with(new Tree())->setChildOf($root); // New child
$sibling    = new Tree();
$sibling->setSiblingOf($child); // New sibling
```

### Getting tree nodes

[](#getting-tree-nodes)

Leaf - returning root node

```
$leaf->findRoot();
```

Children - returning flat collection of children. You can use Eloquent query builder.

```
$collection = $root->children()->get();
$collection2 = $root->children()->where('url', '=', 'slug')->get();
```

Ancestors - returning flat collection of ancestors, first is root, last is current node. You can use Eloquent query builder. Of course there are no guarantees that the structure of the tree would be complete if you do the query with additional where

```
$collection = $node->findAncestors()->get();
$collection2 = $node->findAncestors()->where('url', '=', 'slug')->get();
```

Descendants - returning flat collection of descendants, first is current node, last is leafs. You can use Eloquent query builder. Of course there are no guarantees that the structure of the tree would be complete if you do the query with additional where

```
$collection = $node->findDescendants()->get();
$collection2 = $node->findDescendants()->where('url', '=', 'slug')->get();
```

Building tree structure on PHP side - if some nodes will be missing, these branches will not be built

```
$treeRoot = $root->buildTree($root->findDescendants()->get())
```

### Getting leaf nodes

[](#getting-leaf-nodes)

```
Tree::getLeaves();
```

### Map from array

[](#map-from-array)

Three new roots, first with descendants

```
 Tree::mapArray(
            array(
                array(
                    'children' => array(
                        array(
                            'children' => array(
                                array(
                                    'children' => array(
                                        array(
                                            'children' => array()
                                        ),
                                        array(
                                            'children' => array()
                                        )
                                    )
                                ),
                                array(
                                    'children' => array()
                                )
                            )
                        ),
                        array(
                            'children' => array()
                        )
                    )
                ),
                array(
                    'children' => array()
                ),
                array(
                    'children' => array()
                )
            )
 );
```

### Rendering tree

[](#rendering-tree)

You can render tree built by the function buildTree

```
 $html = $root->render(
        'ul',
        function ($node) {
            return '' . $node->title . '{sub-tree}';
        },
        TRUE
        );
 echo $html;
```

Events
------

[](#events)

All tree models have additional events:

- updatingParent
- updatedParent
- updatedDescendants

You can use them for example to update additional tables

Support
-------

[](#support)

If you enjoy my work, please consider making a small donation, so I can continue to maintain and create new software to help other users.

[![PayPal](https://camo.githubusercontent.com/0293c3ea1e6dbe13508306375f69c8d21d79fce0478eb6f60e84c512d7e5192c/68747470733a2f2f7777772e70617970616c6f626a656374732e636f6d2f656e5f55532f47422f692f62746e2f62746e5f646f6e61746543435f4c472e676966)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6YKG4RZRQF3GS)

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity45

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 93.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~123 days

Recently: every ~177 days

Total

15

Last Release

2803d ago

Major Versions

v0.7 → v1.02015-03-26

v1.0 → v2.02015-06-07

v2.1 → v3.0.02016-10-08

PHP version history (4 changes)v0.1PHP &gt;=5.3.0

v1.0PHP &gt;=5.4.0

v2.1PHP &gt;=5.5.9

v3.0.0PHP &gt;=5.6.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/b6c935886d1946e6478e6c18bc9437fb1944c7e041198e431d028dca8f8189fa?d=identicon)[AdrianSkierniewski](/maintainers/AdrianSkierniewski)

---

Top Contributors

[![AdrianSkierniewski](https://avatars.githubusercontent.com/u/2774458?v=4)](https://github.com/AdrianSkierniewski "AdrianSkierniewski (62 commits)")[![khaledkhamis](https://avatars.githubusercontent.com/u/5251124?v=4)](https://github.com/khaledkhamis "khaledkhamis (2 commits)")[![alustau](https://avatars.githubusercontent.com/u/2944692?v=4)](https://github.com/alustau "alustau (1 commits)")[![carlos3duardo](https://avatars.githubusercontent.com/u/2405236?v=4)](https://github.com/carlos3duardo "carlos3duardo (1 commits)")

---

Tags

composerlaravellaravel-packagephptree-modellaraveleloquent

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/gzero-eloquent-tree/health.svg)

```
[![Health](https://phpackages.com/badges/gzero-eloquent-tree/health.svg)](https://phpackages.com/packages/gzero-eloquent-tree)
```

###  Alternatives

[rtconner/laravel-likeable

Trait for Laravel Eloquent models to allow easy implementation of a 'like' or 'favorite' or 'remember' feature.

394388.0k5](/packages/rtconner-laravel-likeable)[shiftonelabs/laravel-cascade-deletes

Adds application level cascading deletes to Eloquent Models.

163632.1k2](/packages/shiftonelabs-laravel-cascade-deletes)[highsolutions/eloquent-sequence

A Laravel package for easy creation and management sequence support for Eloquent models with elastic configuration.

121130.3k](/packages/highsolutions-eloquent-sequence)[cybercog/laravel-nova-ban

A Laravel Nova banning functionality for your application.

40199.8k](/packages/cybercog-laravel-nova-ban)[phaza/single-table-inheritance

Single Table Inheritance Trait

1515.8k](/packages/phaza-single-table-inheritance)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
