2

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.

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

1 Answers1

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

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

RMcLeod
  • 2,561
  • 1
  • 22
  • 38
Ali Özen
  • 1,525
  • 2
  • 14
  • 29
  • Perfect! Thanks a lot – Yahya Uddin Dec 03 '18 at 09:00
  • `$users = User::all();` is much simpler, don't you think? – Erich May 31 '19 at 14:19
  • yes it does :) I just want to say use "all" instead of "toArray". There is no need for User::get(); Its same for this situation. – Ali Özen Jun 01 '19 at 06:24
  • So, the answer to the actual question of how to "convert Laravel Collection to an array non-recursively" is to use `all()` instead of `toArray()`? I think the answer would have been better if you would have mentioned this, not just "fixed" the asker's code... – rob74 Nov 25 '20 at 17:19