Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Convert Eloquent collection to Array without converting elements

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.

Update / Conclusion

There seems to be a difference between the all method on a Illuminate\Support\Collection and a Illuminate\Database\Eloquent\Collection. The all on an Eloquent Collection returns a Support Collection and the Support Collection returns an Array.

So to get an Array of Eloquent models you need to use SomeModel::all()->all();

like image 698
Arno van Oordt Avatar asked Nov 08 '18 16:11

Arno van Oordt


1 Answers

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.

like image 122
Peter Avatar answered Sep 20 '22 12:09

Peter