I'm working with Laravel on a client project where I want to build a tree structure with the users registered in the system, I found a script that does this, and for that it uses JSONs to get the data.
The framework it works on is as follows:
{
"name": "Top Level",
"parent": null,
"children": [{
"name": "Level 2: A",
"parent": "Top Level",
"children": [{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
I tried to prepare my JSON in the same format but did not understand the logic it will generate from auto-forming. I have a user in my database that as in the example it has "parent": null
in my case: "id_user_parent":null
, and all other users are related to other user IDs.
My question is, how do you let this user know that "id_user_parent":null
first and the rest he popular with their respective children?
My call in my controller:
$users = User::select('name_first', 'name_second', 'id_user_parent')->get()
And the answer JSON from my bank is this:
[
{
"name_first": "Tiago",
"name_second": "Revers Paza",
"id_user_parent": null
},
{
"name_first": "Yuri",
"name_second": "Luiz Hugo da Cunha",
"id_user_parent": 1
},
{
"name_first": "Severino",
"name_second": "Ben\u00edcio das Neves",
"id_user_parent": 1
}
]
That is, how do I format the structure that comes from the response from my database to the structure expected to generate the users tree?