I have a Laravel collection of pages - each page has a "parent_id" property. It resembles this.
"pages": [
{
"id": 1,
"title": "Page 1 Level 1",
"parent_id": 0
},
{
"id": 2,
"title": "Page 2 Level 2",
"parent_id": 1
},
{
"id": 3,
"title": "Page 3 Level 3",
"parent_id": 2
},
{
"id": 4,
"title": "Page 4 Level 1",
"parent_id": 0
},
{
"id": 5,
"title": "Page 5 Level 2",
"parent_id": 4
},
{
"id": 6,
"title": "Page 6 Level 3",
"parent_id": 5
},
{
"id": 7,
"title": "Page 7 Level 1",
"parent_id": 0
},
{
"id": 8,
"title": "Page 8 Level 2",
"parent_id": 7
}
]
What I am trying to do is format the output so they are nested with the correct hierarchy. So for example:
"pages": [
{
"id": 1,
"title": "Page 1 Level 1",
"parent_id": 0,
"children": [
{
"id": 2,
"title": "Page 2 Level 2",
"parent_id": 1,
"children": [
{
"id": 3,
"title": "Page 3 Level 3",
"parent_id": 2,
"children": []
}
]
},
]
},
{
"id": 4,
"title": "Page 4 Level 1",
"parent_id": 0,
"children": [
{
"id": 5,
"title": "Page 5 Level 2",
"parent_id": 4,
"children": [
{
"id": 6,
"title": "Page 6 Level 3",
"parent_id": 5,
"children": []
}
]
},
]
},
{
"id": 7,
"title": "Page 7 Level 1",
"parent_id": 0,
"children": [
{
"id": 8,
"title": "Page 8 Level 2",
"parent_id": 7,
"children": []
},
]
},
]
The hierarchy can be any number of levels deep. I have a nearly working version as shown below, but it does contain a bug. Whilst the various child objects are nesting with their parent, they also remain at the root level. So it looks like duplicates are actually placed in their nested positions.
Can anyone help me finish this off?
PageController
$pages = Page::with('children')->get();
Page
public function directChildren(): HasMany
{
return $this->hasMany($this, 'parent_id', 'id');
}
public function children(): HasMany
{
return $this->directChildren()->with('children'));
}
question from:
https://stackoverflow.com/questions/65941205/flat-laravel-collection-to-tree