Blog User Guide Documentation API Login Register

Documentation > Reference

Collections

Last updated February 16, 2024

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:

$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
    return strtoupper($name);
})
->reject(function ($name) {
    return empty($name);
});

As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.

Creating Collections

As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as:

$collection = collect([1, 2, 3]);

Note

The results of Eloquent queries are always returned as Collection instances.

Available Methods

For the remainder of this documentation, we'll discuss each method available on the Collection class. Remember, all of these methods may be chained to fluently manipulating the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:

Method Listing

all()

The all method returns the underlying array represented by the collection:

collect([1, 2, 3])->all();

// [1, 2, 3]