lundi 3 décembre 2018

Convert Laravel Collection to an array non-recursively

I have an Collection of objects. I want to turn this to an array of objects. Unfortunatley 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($users);

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.

Here is some workarounds I found

Workaround 1

Loop through the collection:

$result = [];
foreach ($users as $user) {
    $result[] = $user;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire