Search

Laravel Collection Public API: all

November 29, 2016 —John Koster

all

The all method can be used to retrieve the underlying array that the collection is using to hold its data. The following code demonstrates the usage of the all method:

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

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

1array (size=2)
2 'first' => string 'I am first' (length=10)
3 'second' => string 'I am second' (length=11)

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

1<?php
2 
3// true
4$areEqual = $items === $returnedItems;

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

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

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

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

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.