Search

Laravel 5 Collections: Retrieving Collection Elements With all

April 22, 2018 —John Koster

The all method can be used to retrieve the underlying array that the collection is using to hold its data.

#Signature

The signature of the all method is:

1public function all();

#Example Use

The following code demonstrates the usage of the all method:

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

After the above code has been executed, the $returnedItems variable would hold the following value:

1array
2 'first' => string 'I am first'
3 'second' => string 'I am second'

We can also verify that the two arrays are indeed equal:

1// true
2$areEqual = $items === $returnedItems;

It should also be noted that the all method will preserve any nested collections:

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->all();

At this point, the $returnedItems variable would a value similar to the following:

1array
2 'first' => string 'I am first'
3 'second' => string 'I am second'
4 'third' =>
5 object(Illuminate\Support\Collection)
6 protected 'items' =>
7 array
8 'first' => string 'I am nested'

To return an array, and have any nested collections converted to arrays, see the toArray method.

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.