Search

An Introduction To Laravel Collections

November 29, 2016 —John Koster

The Illuminate\Support\Collection class provides a wrapper around PHP's arrays. The Collection class has numerous methods for retrieving, setting and manipulating the data of the underlying array. Each Collection instance has an internal array which is used to store the actual collection items.

#Basic Usage - Collections as Arrays

Because Laravel's Collection class is an extravagant wrapper around PHP arrays, its basic usage should be very familiar to most PHP developers. The Collection class also implements PHP's ArrayAccess interface so that developers can use PHP's array syntax when working with collections:

1<?php
2 
3// Creating a new collection instance.
4$collection = new Collection;
5 
6// Appending to the collection.
7$collection[] = 'First';
8$collection[] = 'Second';
9$collection[] = 'Third';
10 
11// Adding key/value pairs to the collection.
12$collection['key'] = 'Some value';
13$collection['key2'] = 'Some other value';
14 
15foreach ($collection as $key => $value) {
16 // Iterate through the array with access to key/value pairs.
17}
18 
19// Retrieve the value associated with a known key.
20$someValue = $collection['key'];

After the above code executes, the variable $someValue would hold the value Some value. It should be noted that even though array syntax works with collections, PHP's array specific functions will not work on an instance of a collection directly. Instead we have to retrieve the underlying array from the collection.

The following code will throw an instance of ErrorException stating that array_values expects the first parameter to be an object:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5$collection = new Collection;
6$collection[] = 'First';
7$collection[] = 'Second';
8$collection[] = 'Third';
9 
10$values = array_values($collection);

Instead, the toArray method can be used to retrieve a representation of the underlying array:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5$collection = new Collection;
6$collection[] = 'First';
7$collection[] = 'Second';
8$collection[] = 'Third';
9 
10$values = array_values($collection->toArray());

After the above code executes, $values would contain a value similar to the following:

1array (size=3)
2 0 => string 'First' (length=5)
3 1 => string 'Second' (length=6)
4 2 => string 'Third' (length=5)

#Notes on Basic Usage

Any caveats that apply when working with arrays in PHP also apply to Collection instances when treating them as arrays. This means that developers have to check for the existence of items themselves when accessing or iterating over the collection. For example, the following code will produce an ErrorException stating that the index does_not_exist does not exist:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5$collection = new Collection;
6 
7$value = $collection['does_not_exist'];

Interacting with collections in this manner should be relatively uncommon in practice. The Collection class provides many methods that aid developers in such situations. As an example, the get method allows retrieval of data from the collection, with the option of returning a default value:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5$collection = new Collection;
6 
7$value = $collection->get('does_not_exist', 'But I do');

After the above code is executed the $value variable would have the value But I do, and the code will not throw an exception. I have an entire series on the Collection's Public API.

#Creating a New Collection Instance

There are a few different ways to create a new Collection instance with existing data. The first way to create a new instance is to pass an array of items to the Collection class's constructor:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// An array of test data.
6$testData = [
7 'first' => 'This is the first',
8 'second' => 'This is the second',
9 'third' => 'This is third'
10];
11 
12// Create a new collection instance.
13$collection = new Collection($testData);

Another way to create a Collection instance is to call the static make method on the Collection class itself:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// An array of test data.
6$testData = [
7 'first' => 'This is the first',
8 'second' => 'This is the second',
9 'third' => 'This is third'
10];
11 
12// Create a new collection instance static 'make' method.
13$collection = Collection::make($testData);

A convenient way to create a new Collection instance is to use the collect helper function. The collect helper function internally returns a new instance of Collection passing in any arguments to the class's constructor. its most basic usage is:

1<?php
2 
3// An array of test data.
4$testData = [
5 'first' => 'This is the first',
6 'second' => 'This is the second',
7 'third' => 'This is third'
8];
9 
10// Create a new collection instance using the 'collect' helper.
11$collection = collect($testData);

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.