Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jay_gorio's avatar

How to place node on specific position(left/right) using laravel-nestedset

I am using the package laravel-nestedset for my multi level marketing(binary) system. However I cannot figure it out how to append the node to specific position.

Let's say for example:

$parent = User::find(1);
$child = User::create(['name' => 'Child', 'username' => 'child1']);
$parent->appendNode($child);

The output will be:

{
        id:1,
        name: 'Parent',
        parent_id: null,
        _lft: 1,
        _rgt:4,
        'username': 'parent1',
        'children: [
            {
                id:2,
                name : 'Child',
                username: 'child1',
                _lft: 2,
                _rgt: 3,
                parent_id: 1
            }
        ]
}

How do I know if the node is positioned on left or right? And what if I only want to fetch the children of parent based on left position?

0 likes
3 replies
Mithrandir's avatar

Left or right of what?

As I understand the package, $parent->appendNode($child) will add $child to $parent. If there are existing children, it will be placed at the bottom.

Also, what do you mean by "fetch [...] based on left position"?

mstrauss's avatar

Sorry for the repeated answer, but the below still applies here:

The package you mentioned seems to have a lot of convenience methods related to using a nested set model for a binary tree in Laravel. (Nested sets being a SQL implementation of a binary tree).

However, the way the child nodes and left/right work in a nested set model doesn't quite work the way your question is described:

For example if the left and right child is empty find the next left empty child and append there?

While it seems the package will take care of the details, with a nested set model, he assignment of the left and right fields to the node have to do with their position beneath the parent node and their position with regard to their sibling nodes respectively. Below are two examples of inserting nodes from the package:

$node->appendToNode($parent)->save();

Or

$node->afterNode($neighbor)->save();

As you can see the package will handle the right/left assignments.

To learn more about how nested sets work check out this really nice, straight forward article on the subject: https://falsinsoft.blogspot.com/2013/01/tree-in-sql-database-nested-set-model.html

jay_gorio's avatar

Thank you for your response. That is why I like the package it has a lot of convenience. However, based on your answer and the documentation itself, user has no control of manually assigning the node position. Anyways thank your for the reference.

Please or to participate in this conversation.