Laravel flatten collection by multidimensional objects with same property

  collections, laravel, php

I have an array of Field objects. This object has a property called fields which contain another array of fields. This can go infinitely deep.

So what I want to do is create a flattened collection of all the parent fields, their child fields, their childs child fields…all the way down.

I have this which works great, but it only goes 1 level deep:

    $fields = collect();

    foreach ($model->fields() as $field) {
        $fields->push($field, $field->fields);

    return $fields->filter()->flatten();

How do I add infinite recursion to this which will flatten the final results?

Source: Laravel

Leave a Reply