We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
What
If a nested array is passed into a Laravel Collection, by default these will be threaded as normal arrays.
However, that's not always the ideal case and it would be nice if we could have nested collections in a cleaner way.
This is where this macro comes in handy.
Setup
Register this macro for example on the boot method of your app\Providers\AppServiceProvider.php file:
\Illuminate\Support\Collection::macro('recursive', function () { return $this->map(function ($value) { if (is_array($value) || is_object($value)) { return collect($value)->recursive(); } return $value; }); });
How
Usage is quite simple:
$data = [ [ 'name' => 'John Doe', 'emails' => [ 'john@doe.com', 'john.doe@example.com', ], 'contacts' => [ [ 'name' => 'Richard Tea', 'emails' => [ 'richard.tea@example.com', ], ], [ 'name' => 'Fergus Douchebag', // Ya, this was randomly generated for me :) 'emails' => [ 'fergus@douchebag.com', ], ], ], ], ]; $collection = collect($data)->recursive();
continue reading on gist.github.com
⚠️ This post links to an external website. ⚠️
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.