Collections

Introduction

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, 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]);

By default, collections of Eloquent models are always returned as Collection instances; however, feel free to use the Collection class wherever it is convenient for your application.

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 for 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.

You may select any method from this table to see an example of its usage:

[all](#method-all) [avg](#method-avg) [chunk](#method-chunk) [collapse](#method-collapse) [contains](#method-contains) [count](#method-count) [diff](#method-diff) [each](#method-each) [every](#method-every) [except](#method-except) [filter](#method-filter) [first](#method-first) [flatten](#method-flatten) [flip](#method-flip) [forget](#method-forget) [forPage](#method-forpage) [get](#method-get) [groupBy](#method-groupby) [has](#method-has) [implode](#method-implode) [intersect](#method-intersect) [isEmpty](#method-isempty) [keyBy](#method-keyby) [keys](#method-keys) [last](#method-last) [map](#method-map) [max](#method-max) [merge](#method-merge) [min](#method-min) [only](#method-only) [pluck](#method-pluck) [pop](#method-pop) [prepend](#method-prepend) [pull](#method-pull) [push](#method-push) [put](#method-put) [random](#method-random) [reduce](#method-reduce) [reject](#method-reject) [reverse](#method-reverse) [search](#method-search) [shift](#method-shift) [shuffle](#method-shuffle) [slice](#method-slice) [sort](#method-sort) [sortBy](#method-sortby) [sortByDesc](#method-sortbydesc) [splice](#method-splice) [sum](#method-sum) [take](#method-take) [toArray](#method-toarray) [toJson](#method-tojson) [transform](#method-transform) [unique](#method-unique) [values](#method-values) [where](#method-where) [whereLoose](#method-whereloose) [whereIn](#method-wherein) [whereInLoose](#method-whereinloose) [zip](#method-zip)

Method Listing

all() {#collection-method .first-collection-method}

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

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

// [1, 2, 3]

avg() {#collection-method}

The avg method returns the average of all items in the collection:

collect([1, 2, 3, 4, 5])->avg();

// 3

If the collection contains nested arrays or objects, you should pass a key to use for determining which values to calculate the average:

$collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);

$collection->avg('pages');

// 636

chunk() {#collection-method}

The chunk method breaks the collection into multiple, smaller collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

This method is especially useful in views when working with a grid system such as Bootstrap. Imagine you have a collection of Eloquent models you want to display in a grid:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach

collapse() {#collection-method}

The collapse method collapses a collection of arrays into a flat collection:

$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

$collapsed = $collection->collapse();

$collapsed->all();

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

contains() {#collection-method}

The contains method determines whether the collection contains a given item:

$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');

// true

$collection->contains('New York');

// false

You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->contains('product', 'Bookcase');

// false

Finally, you may also pass a callback to the contains method to perform your own truth test:

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

$collection->contains(function ($key, $value) {
    return $value > 5;
});

// false

count() {#collection-method}

The count method returns the total number of items in the collection:

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

$collection->count();

// 4

diff() {#collection-method}

The diff method compares the collection against another collection or a plain PHP array:

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

$diff = $collection->diff([2, 4, 6, 8]);

$diff->all();

// [1, 3, 5]

each() {#collection-method}

The each method iterates over the items in the collection and passes each item to a given callback:

$collection = $collection->each(function ($item, $key) {
    //
});

Return false from your callback to break out of the loop:

$collection = $collection->each(function ($item, $key) {
    if (/* some condition */) {
        return false;
    }
});

every() {#collection-method}

The every method creates a new collection consisting of every n-th element:

$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

$collection->every(4);

// ['a', 'e']

You may optionally pass offset as the second argument:

$collection->every(4, 1);