Skip to content

Instantly share code, notes, and snippets.

@hasnhasan
Created June 30, 2020 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasnhasan/f4da71323b35d4bef5a21158200560c9 to your computer and use it in GitHub Desktop.
Save hasnhasan/f4da71323b35d4bef5a21158200560c9 to your computer and use it in GitHub Desktop.
reverseNested
use Illuminate\Support\Collection;
Collection::macro('reverseNested', function ($childrenField,$parents=[]) {
$result = collect();
foreach ($this->items as $item) {
if ($item->$childrenField) {
$parents[] = $item->name;
$subCategories = collect($item->$childrenField)->map(function($cat) use ($parents){
$cat->parents = $parents;
return $cat;
});
unset($item->$childrenField);
$result = $result->merge($subCategories->reverseNested($childrenField,$parents));
} else {
unset($item->$childrenField);
$result->push($item);
}
}
return $result;
});
// Usage
$categories = collect($categories);
$reverseCategories = $categories->reverseNested('subCategories');
dd($reverseCategories);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment