To convert a Laravel collection to an array, you can use the toArray
method on the collection. This method will return an array with the items in the collection.
Here’s an example:
$collection = collect([1, 2, 3, 4]);
$array = $collection->toArray();
// $array is now [1, 2, 3, 4]
The toArray
method will recursively convert all nested collections to arrays as well.
If you want to preserve the keys of the items in the collection, you can use the all
method instead:
$collection = collect(['a' => 1, 'b' => 2, 'c' => 3]);
$array = $collection->all();
// $array is now ['a' => 1, 'b' => 2, 'c' => 3]
Both the toArray
and all
methods return a plain PHP array, they do not return an instance of the Illuminate\Support\Collection
class.
If you want to convert the collection back to a collection object after converting it to an array, you can use the collect
helper function:
$array = [1, 2, 3, 4];
$collection = collect($array);
// $collection is now a collection object containing [1, 2, 3, 4]