Search code examples
phplaravellaravel-5laravel-collection

Convert Laravel Collection to an array non-recursively


I have an Collection of objects. I want to turn this to an array of objects. Unfortunately the toArray in Collection seems to apply recursively, and thus I actually get an array of arrays.

Here is an example showing the problem:

$users = User::get();
$result = $users->toArray();
dd($result);

In the above example, instead of getting an array of User models, you get an array of arrays.

It is clear why this issue occurs when you look at Laravel's source code:

// Illuminate\Support\Collection.php

public function toArray()
{
    return array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $this->items);
}

Please note I still want $users to be a Collection, as the example is just a MCVE. I just don't want toArray to be applied recursively. Note that I am fully aware of bad workarounds such as re-hydrating my models.


Solution

  • $users = User::get();
    $result = $users->all();
    dd($result);
    

    I think this is what you want. Give it a try.