/Laravel

Laravel collection multidimensional arrays recursive

When I use the laravel collection recursive I find it’s very nice but it’s only supported the arrays of one dimensional. I need to do it support multidimensional arrays now.


It’s a good idea to use the macroable extending collection, here is a solution. Register the macro in boot method within your app\Providers\AppServiceProvider.php:

\Illuminate\Support\Collection::macro('recursive', function () {
    return $this->map(function ($value) {
        if (is_array($value) || is_object($value)) {
            return collect($value)->recursive();
        }

        return $value;
    });
});

solution

Thanks for @brunogaspar provides the idea!

Yish

Yish

The creator of yish.dev

Read More