Suppose I have the following laravel collection:
[
{id: 1, name: 'Home', folder_id: null},
{id: 2, name: 'Documents', folder_id: 1},
{id: 3, name: 'Media', folder_id: 1 },
{id: 4, name: 'Photos', folder_id: 3},
{id: 5, name: 'Videos', folder_id: 3},
{id: 6, name: 'Invoices', folder_id: 2},
{id: 7, name: 'Games', folder_id: 1}
]
folder_id is a foreign key is a row to the direct parent.
I would like to iterate through the collection and create a folder tree looking like this using blade templating engine:
- Home
- Documents
- Invoices
- Media
- Photos
- Videos
- Documents
- Games
Each element in the collection is of instance Folder with the following eloquent relationships defined:
public function folder(){
return $this->belongsTo(Folder::class);
}
public function folders(){
return $this->hasMany(Folder::class);
}