kazehaya's avatar

How to build a tree structure with the help of eloquent

Im trying to make a tree structure depending on the parent_id.

let me first show my database structure:

- id
- parent_id
- title

What i have tried is to order by parent_id for the sub items like this and check if the parent_id is equal to null for the root items:

        $root_items = Item::whereNull('parent_id')->get();
        $child_items = Item::groupby('parent_id')->get();

I have no clue how i can make a tree structure array that every child item goes under there belonging parent item.

Is someone kind enough to help me in the right direction with this?

0 likes
4 replies
kazehaya's avatar

@kfirba I have seen those packages but i think its overkill for what im asking, or am i wrong? :/

kfirba's avatar

@kazehaya As suggested here you can do something like that:

$items = Item::all();

$tree = [];

foreach($items as $item) {
    $pid  = $row->parent_id;
  $id   = $row->id;
    $name = $row->name;

    // Create or add child information to the parent node
    if (isset($tree[$pid]))
        // a node for the parent exists
        // add another child id to this parent
        $tree[$pid]["children"][] = $id;
    else
        // create the first child to this parent
        $tree[$pid] = array("children"=>array($id));

    // Create or add name information for current node
    if (isset($tree[$id]))
        // a node for the id exists:
        // set the name of current node
        $tree[$id]["name"] = $name;
    else
        // create the current node and give it a name
        $tree[$id] = array( "name"=>$name );
}

// $tree now holds the structure

otepas's avatar

@kazehaya It depends on how you look at it. Both are solid and tested packages that you can install and be using in minutes. You might be using 10% of what they offer, but you know it is going to work.

On the other hand you can spend time coding and testing a solution that fits exactly what you need.

Depending on your needs / point of view either could be considered an overkill. If you are focusing on productivity and have a solution as soon as possible, one of those packages might be the best option. If you are focusing on learning and improving your skills, it might be better to code your own solution. In my opinion there is no right or wrong answer.

Please or to participate in this conversation.