Laravel Collection Public API: collapse

November 29, 2016 —John Koster

collapse

The collapse method combines all the first-level items of a collection into a new, single collection. The returned value of the collapse method is an instance of the Collection class.

We will create a simple collection to work with like this:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5$first = [
6 0, 1, 2, 3, 4
7];
8 
9$second = [
10 5, 6, 7, 8 , 9
11];
12 
13$collection = new Collection([$first, $second]);

The $collection variable now has an internal structure similar to the following output:

1object(Illuminate\Support\Collection)[132]
2 protected 'items' =>
3 array (size=2)
4 0 =>
5 array (size=5)
6 0 => int 0
7 1 => int 1
8 2 => int 2
9 3 => int 3
10 4 => int 4
11 1 =>
12 array (size=5)
13 0 => int 5
14 1 => int 6
15 2 => int 7
16 3 => int 8
17 4 => int 9

We can see that our collection contains two arrays. Using the collapse method, we can get a Collection instance that combines the two arrays above:

1<?php
2 
3$collapsed = $collection->collapse();

Now, the $collapsed variable would have a value similar to the following:

1object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=10)
4 0 => int 0
5 1 => int 1
6 2 => int 2
7 3 => int 3
8 4 => int 4
9 5 => int 5
10 6 => int 6
11 7 => int 7
12 8 => int 8
13 9 => int 9

The collapse method internally calls the Illuminate\Support\Arr::collapse($array) helper function. It will collapse both nested arrays and Collection instances.

It should be noted that the collapse method does not recursively collapse inner arrays. The following code sample will create another collection, this time with a nested array:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5$first = [
6 0, 1, 2, 3, 4
7];
8 
9$second = [
10 [5, 6, 7, 8 , 9]
11];
12 
13$collection = new Collection([$first, $second]);

If we collapsed the $collection, the result would be similar to the following output:

1object(Illuminate\Support\Collection)[133]
2 protected 'items' =>
3 array (size=6)
4 0 => int 0
5 1 => int 1
6 2 => int 2
7 3 => int 3
8 4 => int 4
9 5 =>
10 array (size=5)
11 0 => int 5
12 1 => int 6
13 2 => int 7
14 3 => int 8
15 4 => int 9

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.