Skip to content

Instantly share code, notes, and snippets.

@ddavaham
Forked from brunogaspar/macro.md
Created December 2, 2017 17:59
Show Gist options
  • Save ddavaham/3fcf7d0d4e24445b7cb61375405558b9 to your computer and use it in GitHub Desktop.
Save ddavaham/3fcf7d0d4e24445b7cb61375405558b9 to your computer and use it in GitHub Desktop.
Recursive Laravel Collection Macros

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 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)) {
            return collect($value)->recursive();
        }

        return $value;
    });
});

Note: Tested only on Laravel 5.5!

How

Usage is quite simple:

$data = [
    [
        'name' => 'John Doe',
        'emails' => [
            '[email protected]',
            '[email protected]',
        ],
        'contacts' => [
            [
                'name' => 'Richard Tea',
                'emails' => [
                    '[email protected]',
                ],
            ],
            [
                'name' => 'Fergus Douchebag', // Ya, this was randomly generated for me :)
                'emails' => [
                    '[email protected]',
                ],
            ],
        ],
    ],
];

$collection = collect($data)->recursive();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment