Laravel’s Collection
class is awesome. Probably you use it in all of your Laravel projects.
Something that you’ll need to often is casting the collection back to a regular array. Like me, you might be tempted to use toArray()
for this. But that might be the wrong method to call.
On a simple collection toArray
works like expected.
$collection = collect([1, 2, 3]);
$collection->toArray(); // returns [1, 2, 3]
But here’s an example where it doesn’t behave like you might expect. Let’s try calling toArray
on a collection of Eloquent models.
$usersCollection = User::all(); // returns a collection
$usersArray = $usersCollection->toArray();
ray($usersArray);
Let’s take a look at what that returns in Ray.

As you can see, the models inside of the collection have been casted to arrays as well. This might be something you did not expect.
To get all elements out of the collection as an array, you must call all()
instead of toArray()
.
$usersCollection = User::all(); // returns a collection
$usersArray = $usersCollection->all();
ray($usersArray);
In Ray, you can now see, that the array holds instances of User
models.
