Laravel: Convert Eloquent collection to Array without converting elements [duplicate]
Asked Answered
B

2

13

Is there a (simple) way to convert an Eloquent Collection to an actual array without converting the elements themselves?

I get in trouble when I try to pass the collection into a php method like array_rand($collection). This gives me the error: array_rand() expects parameter 1 to be array, object given.

I worked around this by using $collection->shuffle()->first(); which works fine and of course I could loop over the collection and push all in an array, but just out of curiosity I wonder if I'm overlooking something.

Bothnia answered 8/11, 2018 at 16:16 Comment(0)
H
16

My first thought was $collection->toArray() but that also converts the Eloquent models to arrays. But the docs say that $collection->all() should avoid that.

toArray also converts all of the collection's nested objects to an array. If you want to get the raw underlying array, use the all method instead.

Hitlerism answered 8/11, 2018 at 16:48 Comment(0)
K
7

You can use the all collection helper:

The all method returns the underlying array represented by the collection:

collect([1, 2, 3])->all();

// [1, 2, 3]
Krupp answered 8/11, 2018 at 16:49 Comment(1)
Ah, this seems to work for 'Illuminate\Support\Collection' indeed. Since I was getting the collection from an Eloquent model ('Illuminate\Database\Eloquent\Collection') I was under the impression that the all I used SomeModel::all() was already the same. But now I see that I need to do another all-call on the result: SomeModel::all()->all().Bothnia

© 2022 - 2024 — McMap. All rights reserved.