Laravel swapping rows of menu, submenus in DB

Question is not big and not BROAD. Please try to read and answer this. I am trying this from long time.


Structure:

I have a menus table, oriented in this way: enter image description here

enter image description here

id column is primary key. child_of column is foreign key referencing id column, it is used for acting like a submenu.

Code

My code starts by removing primary, foreign keys and saving Auto increment value. This value is used back in the end after process while setting keys again. Code explained in end.

DB::transaction(function ($tree) use ($tree) {
    $count = 1;

    //Removing foreign, primary keys 
    //and saving Autoincrement value. That code comes here.


//MAIN CODE:
for ($i = 0; $i < count($tree); $i++) {
    DB::statement('UPDATE menus, menus as t2 SET menus.id = t2.id, t2.id = menus.id, menus.child_of = NULL WHERE menus.id = ? AND t2.id = ?', [$tree[$i]['id'], $count]);
    $parent = $count;
    $count++;
    if(isset($tree[$i]['children'])) {
        for ($j = 0; $j < count($tree[$i]['children']); $j++, $count++) {
        DB::statement('UPDATE menus, menus as t2 SET menus.id = t2.id, t2.id = menus.id, menus.child_of = ? WHERE menus.id = ? AND t2.id = ?', [$parent, $tree[$i]['children'][$j]['id'], $count]);
        }
    }

}

    //Setting Primary, Foreign keys back and setting AutoIncrement value code comes here.

});

Example Input:

[{"id":1},{"id":3,"children":[{"id":4},{"id":5}]}]

So what is happening in process:

  1. I am parsing through each object in array, and setting id value of object in numerical order, id:1 will be placed as 1 in DB, id:3 will be placed as 2.

  2. If there is children( like in input example) I will continue the order. Like id:3 has 2 children. id:4 and id:5. So, id:4 will have id=3, id:5 will have id=4 in DB and I will set child_of value as parent's id value. That is child_of=2.

  3. For parent, I will set child_of value as NULL.

What's the output?

It's disrupting the menu, some items gets jumbled updown. I am not able to traceback what's wrong in my code.

If you've any other logic please share it. THANKS.

What's the purpose?

I am using this with Nestable for reordering menu items.


Thanks alot if you read my problem.