Skip to content

Instantly share code, notes, and snippets.

@andyg1
Created August 25, 2023 08:38
Show Gist options
  • Save andyg1/84b964d81aeeb9c418890fdeb20fb855 to your computer and use it in GitHub Desktop.
Save andyg1/84b964d81aeeb9c418890fdeb20fb855 to your computer and use it in GitHub Desktop.
Laravel - convert an array including its children to Collections
<?php
// source: https://laravel-code.tips/add-a-recursive-macro-to-convert-an-array-including-its-children-to-collections/
// Pop this in boot() of a service provider
Collection::macro('recursive', function () {
return $this->map(function ($value) {
if (is_array($value) || is_object($value)) {
return collect($value)->recursive();
}
return $value;
});
// Usage
collect($array)->recursive();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment