Below my Laravel controller code
public function templateValueData($template_id)
{
$parent = TemplateMetadataValue::where('template_id', $template_id)->get();
return $parent;
}
Here, the output of the method above;
[
{
"id": 11,
"parent_id": 0,
"name": "Category 1"
},
{
"id": 63,
"parent_id": 11,
"name": "Category 2"
},
{
"id": 73,
"parent_id": 63,
"name": "Category 3"
},
{
"id": 77,
"parent_id": 11,
"name": "Category 5"
},
{
"id": 83,
"parent_id": 77,
"name": "Category 8"
}
]
Now I want to format this response base on the value of parent_id.
The condition is: when parent_id is equal to id, then the parent_id is considered as children of the id.
Please note that both parent_id and id are stored as incremental values.
I want to alter and return the response as below;
[
{
"id": 11,
"parent_id": 0,
"name": "Category 1",
"children": [
{
"id": 63,
"parent_id": 11,
"name": "Category 2",
"children": [
{
"id": 73,
"parent_id": 63,
"name": "Category 3"
}
]
},
{
"id": 77,
"parent_id": 11,
"name": "Category 5",
"children": [
{
"id": 83,
"parent_id": 77,
"name": "Category 8"
}
]
}
]
}
]
How can I achieve this?