Laravel 5 Collections: Convert a Collection to a Native PHP Array With toArray

April 22, 2018 —John Koster

The toArray method is similar to the all method in that it will return the underlying array that the collection instance is using. The difference, however, is that the toArray method will convert any object instance it can into arrays (namely any object that implements the "Illuminate\Contracts\Support\Arrayable" interface).

#Signature

The signature of the toArray method is:

1public function toArray();

#Example Use

Consider the following code:

1use Illuminate\Support\Collection;
2 
3$items = [
4 'first' => 'I am first',
5 'second' => 'I am second',
6 'third' => new Collection([
7 'first' => 'I am nested'
8 ])
9];
10 
11$collection = Collection::make($items);
12 
13$returnedItems = $collection->toArray();

After the above code has executed, the $returnedItems variable would contain a value similar to the following output:

1array
2 'first' => string 'I am first'
3 'second' => string 'I am second'
4 'third' =>
5 array
6 'first' => string 'I am nested'

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.