Collections

October CMS Documentation Docs

Collections

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

$collection = new October\Rain\Support\Collection(['stewie', 'brian', null]);

$collection = $collection
    ->map(function ($name) {
        return strtoupper($name);
    })
    ->reject(function ($name) {
        return empty($name);
    })
;

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 described above, passing an array to the constructor of the October\Rain\Support\Collection class will return a new instance for the given array. So, creating a collection is as simple as:

$collection = new October\Rain\Support\Collection([1, 2, 3]);

By default, collections of database 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:

# Method Listing

# all()

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

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

$collection->all();

// [1, 2, 3]

# average()

Alias for the avg method.

# avg()

The avg method returns the average value (opens new window) of a given key:

$average = new Collection([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');

// 20

$average = new Collection([1, 1, 2, 4])->avg();

// 2

# chunk()

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

$collection = new Collection([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 CMS pages when working with a grid system, such as Bootstrap (opens new window). Imagine you have a collection of models you want to display in a grid:

{% for chunk in products.chunk(3) %}
    <div class="row">
        {% for product in chunk %}
            <div class="col-xs-4">{{ product.name }}</div>
        {% endfor %}
    </div>
{% endfor %}

# collapse()

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

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

$collapsed = $collection->collapse();

$collapsed->all();

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

# combine()

The combine method combines the values of the collection, as keys, with the values of another array or collection.

$collection = new Collection(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]

# concat()

The concat method appends the given array or collection values onto the end of the collection:

$collection = new Collection(['John Doe']);

$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);

$concatenated->all();

// ['John Doe', 'Jane Doe', 'Johnny Doe']

# contains()

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

$collection = new Collection(['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 = new Collection([
    ['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 = new Collection([1, 2, 3, 4, 5]);

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

// false

The contains method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the containsStrict method to filter using "strict" comparisons.

# containsStrict()

This method has the same signature as the contains method; however, all values are compared using "strict" comparisons.

# count()

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

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

$collection->count();

// 4

# countBy()

The countBy method counts the occurrences of values in the collection. By default, the method counts the occurrences of every element:

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

$counted = $collection->countBy();

$counted->all();

// [1 => 1, 2 => 3, 3 => 1]

However, you pass a callback to the countBy method to count all items by a custom value:

$collection = new Collection(['alice@gmail.tld', 'bob@yahoo.tld', 'carlos@gmail.tld']);

$counted = $collection->countBy(function ($email) {
    return substr(strrchr($email, "@"), 1);
});

$counted->all();

// ['gmail.tld' => 2, 'yahoo.tld' => 1]

# crossJoin()

The crossJoin method cross joins the collection's values among the given arrays or collections, returning a Cartesian product with all possible permutations:

$collection = new Collection([1, 2]);

$matrix = $collection->crossJoin(['a', 'b']);

$matrix->all();

/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/

$collection = new Collection([1, 2]);

$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);

$matrix->all();

/*
    [
        [1, 'a', 'I'],
        [1, 'a', 'II'],
        [1, 'b', 'I'],
        [1, 'b', 'II'],
        [2, 'a', 'I'],
        [2, 'a', 'II'],
        [2, 'b', 'I'],
        [2, 'b', 'II'],
    ]
*/

# dd()

The dd method dumps the collection's items and ends execution of the script:

$collection = new Collection(['John Doe', 'Jane Doe']);

$collection->dd();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/

If you do not want to stop executing the script, use the dump method instead.

# diff()

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

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

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

$diff->all();

// [1, 3, 5]

# diffAssoc()

The diffAssoc method compares the collection against another collection or a plain PHP array based on its keys and values. This method will return the key / value pairs in the original collection that are not present in the given collection:

$collection = new Collection([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6
]);

$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6,
]);

$diff->all();

// ['color' => 'orange', 'remain' => 6]

# diffKeys()

The diffKeys method compares the collection against another collection or a plain PHP array based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection:

$collection = new Collection([
    'one' => 10,
    'two' => 20,
    'three' => 30,
    'four' => 40,
    'five' => 50,
]);

$diff = $collection->diffKeys([
    'two' => 2,
    'four' => 4,
    'six' => 6,
    'eight' => 8,
]);

$diff->all();

// ['one' => 10, 'three' => 30, 'five' => 50]

# dump()

The dump method dumps the collection's items:

$collection = new Collection(['John Doe', 'Jane Doe']);

$collection->dump();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/

If you want to stop executing the script after dumping the collection, use the dd method instead.

# duplicates()

The duplicates method retrieves and returns duplicate values from the collection:

$collection = new Collection(['a', 'b', 'a', 'c', 'b']);

$collection->duplicates();

// [2 => 'a', 4 => 'b']

If the collection contains arrays or objects, you can pass the key of the attributes that you wish to check for duplicate values:

$employees = new Collection([
    ['email' => 'samantha@example.tld', 'position' => 'Developer'],
    ['email' => 'john@example.tld', 'position' => 'Designer'],
    ['email' => 'elaine@example.tld', 'position' => 'Developer'],
])

$employees->duplicates('position');

// [2 => 'Developer']

# duplicatesStrict()

This method has the same signature as the duplicates method; however, all values are compared using "strict" comparisons.

# each()

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

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

If you would like to stop iterating through the items, you may return false from your callback:

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

# every()

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

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

$collection->every(4);

// ['a', 'e']

You may optionally pass offset as the second argument:

$collection->every(4, 1);

// ['b', 'f']

# filter()

The filter method filters the collection by a given callback, keeping only those items that pass a given truth test:

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

$filtered = $collection->filter(function ($item) {
    return $item > 2;
});

$filtered->all();

// [3, 4]

For the inverse of filter, see the reject method.

# first()

The first method returns the first element in the collection that passes a given truth test:

new Collection([1, 2, 3, 4])->first(function ($value, $key) {
    return $value > 2;
});

// 3

You may also call the first method with no arguments to get the first element in the collection. If the collection is empty, null is returned:

new Collection([1, 2, 3, 4])->first();

// 1

# firstWhere()

The firstWhere method returns the first element in the collection with the given key / value pair:

$collection = new Collection([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);

$collection->firstWhere('name', 'Linda');

// ['name' => 'Linda', 'age' => 14]

You may also call the firstWhere method with an operator:

$collection->firstWhere('age', '>=', 18);

// ['name' => 'Diego', 'age' => 23]

Like the where method, you may pass one argument to the firstWhere method. In this scenario, the firstWhere method will return the first item where the given item key's value is "truthy":

$collection->firstWhere('age');

// ['name' => 'Linda', 'age' => 14]

# flatMap()

The flatMap method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by a level:

$collection = new Collection([
    ['name' => 'Sally'],
    ['school' => 'Harvard'],
    ['age' => 28]
]);

$flattened = $collection->flatMap(function ($values) {
    return array_map('strtoupper', $values);
});

$flattened->all();

// ['name' => 'SALLY', 'school' => 'HARVARD', 'age' => '28'];

# flatten()

The flatten method flattens a multi-dimensional collection into a single dimension:

$collection = new Collection(['name' => 'peter', 'languages' => ['php', 'javascript']]);

$flattened = $collection->flatten();

$flattened->all();

// ['peter', 'php', 'javascript'];

# flip()

The flip method swaps the collection's keys with their corresponding values:

$collection = new Collection(['name' => 'peter', 'platform' => 'october']);

$flipped = $collection->flip();

$flipped->all();

// ['peter' => 'name', 'october' => 'platform']

# forget()

The forget method removes an item from the collection by its key:

$collection = new Collection(['name' => 'peter', 'platform' => 'october']);

$collection->forget('name');

$collection->all();

// ['platform' => 'october']

Note: Unlike most other collection methods, forget does not return a new modified collection; it modifies the collection it is called on.

# forPage()

The forPage method returns a new collection containing the items that would be present on a given page number:

$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9])->forPage(2, 3);

$collection->all();

// [4, 5, 6]

The method requires the page number and the number of items to show per page, respectively.

# get()

The get method returns the item at a given key. If the key does not exist, null is returned:

$collection = new Collection(['name' => 'peter', 'platform' => 'october']);

$value = $collection->get('name');

// peter

You may optionally pass a default value as the second argument:

$collection = new Collection(['name' => 'peter', 'platform' => 'october']);

$value = $collection->get('foo', 'default-value');

// default-value

You may even pass a callback as the default value. The result of the callback will be returned if the specified key does not exist:

$collection->get('email', function () {
    return 'default-value';
});

// default-value

# groupBy()

The groupBy method groups the collection's items by a given key:

$collection = new Collection([
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
            ['account_id' => 'account-x10', 'product' => 'Chair'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

In addition to passing a string key, you may also pass a callback. The callback should return the value you wish to key the group by:

$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item['account_id'], -3);
});

$grouped->toArray();

/*
    [
        'x10' => [
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
            ['account_id' => 'account-x10', 'product' => 'Chair'],
        ],
        'x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

# has()

The has method determines if a given key exists in the collection:

$collection = new Collection(['account_id' => 1, 'product' => 'Desk']);

$collection->has('email');

// false

# implode()

The implode method joins the items in a collection. Its arguments depend on the type of items in the collection.

If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the "glue" string you wish to place between the values:

$collection = new Collection([
    ['account_id' => 1, 'product' => 'Chair'],
    ['account_id' => 2, 'product' => 'Desk'],
]);

$collection->implode('product', ', ');

// Chair, Desk

If the collection contains simple strings or numeric values, simply pass the "glue" as the only argument to the method:

new Collection([1, 2, 3, 4, 5])->implode('-');

// '1-2-3-4-5'

# intersect()

The intersect method removes any values that are not present in the given array or collection:

$collection = new Collection(['Desk', 'Sofa', 'Chair']);

$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

$intersect->all();

// [0 => 'Desk', 2 => 'Chair']

As you can see, the resulting collection will preserve the original collection's keys.

# intersectByKeys()

The intersectByKeys method removes any keys from the original collection that are not present in the given array or collection:

$collection = new Collection([
    'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);

$intersect = $collection->intersectByKeys([
    'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);

$intersect->all();

// ['type' => 'screen', 'year' => 2009]

# isEmpty()

The isEmpty method returns true if the collection is empty; otherwise false is returned:

new Collection([])->isEmpty();

// true

# isNotEmpty()

The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned:

new Collection([])->isNotEmpty();

// false

# join()

The join method joins the collection's values with a string:

new Collection(['a', 'b', 'c'])->join(', '); // 'a, b, c'
new Collection(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
new Collection(['a', 'b'])->join(', ', ' and '); // 'a and b'
new Collection(['a'])->join(', ', ' and '); // 'a'
new Collection([])->join(', ', ' and '); // ''

# keyBy()

Keys the collection by the given key:

$collection = new Collection([
    ['product_id' => 'prod-100', 'name' => 'chair'],
    ['product_id' => 'prod-200', 'name' => 'desk'],
]);

$keyed = $collection->keyBy('product_id');

$keyed->all();

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Chair'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Desk'],
    ]
*/

If multiple items have the same key, only the last one will appear in the new collection.

You may also pass your own callback, which should return the value to key the collection by:

$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});

$keyed->all();

/*
    [
        'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Chair'],
        'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Desk'],
    ]
*/

# keys()

The keys method returns all of the collection's keys:

$collection = new Collection([
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Chair'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Desk'],
]);

$keys = $collection->keys();

$keys->all();

// ['prod-100', 'prod-200']

# last()

The last method returns the last element in the collection that passes a given truth test:

new Collection([1, 2, 3, 4])->last(function ($key, $value) {
    return $value < 3;
});

// 2

You may also call the last method with no arguments to get the last element in the collection. If the collection is empty then null is returned.

new Collection([1, 2, 3, 4])->last();

// 4

# map()

The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

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

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]

Note: Like most other collection methods, map returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the transform method.

# mapInto()

The mapInto() method iterates over the collection, creating a new instance of the given class by passing the value into the constructor:

class Currency
{
    /**
     * Create a new currency instance.
     *
     * @param  string  $code
     * @return void
     */
    function __construct(string $code)
    {
        $this->code = $code;
    }
}

$collection = new Collection(['AUD', 'USD', 'GBP']);

$currencies = $collection->mapInto(Currency::class);

$currencies->all();

// [Currency('AUD'), Currency('USD'), Currency('GBP')]

# mapSpread()

The mapSpread method iterates over the collection's items, passing each nested item value into the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

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

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

$sequence = $chunks->mapSpread(function ($even, $odd) {
    return $even + $odd;
});

$sequence->all();

// [1, 5, 9, 13, 17]

# mapToGroups()

The mapToGroups method groups the collection's items by the given callback. The callback should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:

$collection = new Collection([
    [
        'name' => 'John Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Jane Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Johnny Doe',
        'department' => 'Marketing',
    ]
]);

$grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
});

$grouped->toArray();

/*
    [
        'Sales' => ['John Doe', 'Jane Doe'],
        'Marketing' => ['Johnny Doe'],
    ]
*/

$grouped->get('Sales')->all();

// ['John Doe', 'Jane Doe']

# mapWithKeys()

The mapWithKeys method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair:

$collection = new Collection([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.tld'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.tld'
    ]
]);

$keyed = $collection->mapWithKeys(function ($item) {
    return [$item['email'] => $item['name']];
});

$keyed->all();

/*
    [
        'john@example.tld' => 'John',
        'jane@example.tld' => 'Jane',
    ]
*/

# max()

The max method returns the maximum value of a given key:

$max = new Collection([['foo' => 10], ['foo' => 20]])->max('foo');

// 20

$max = new Collection([1, 2, 3, 4, 5])->max();

// 5

# median()

The median method returns the median value (opens new window) of a given key:

$median = new Collection([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');

// 15

$median = new Collection([1, 1, 2, 4])->median();

// 1.5

# merge()

The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:

$collection = new Collection(['product_id' => 1, 'price' => 100]);

$merged = $collection->merge(['price' => 200, 'discount' => false]);

$merged->all();

// ['product_id' => 1, 'price' => 200, 'discount' => false]

If the given items's keys are numeric, the values will be appended to the end of the collection:

$collection = new Collection(['Desk', 'Chair']);

$merged = $collection->merge(['Bookcase', 'Door']);

$merged->all();

// ['Desk', 'Chair', 'Bookcase', 'Door']

# mergeRecursive()

The mergeRecursive method merges the given array or collection recursively with the original collection. If a string key in the given items matches a string key in the original collection, then the values for these keys are merged together into an array, and this is done recursively:

$collection = new Collection(['product_id' => 1, 'price' => 100]);

$merged = $collection->mergeRecursive(['product_id' => 2, 'price' => 200, 'discount' => false]);

$merged->all();

// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]

# min()

The min method returns the minimum value of a given key:

$min = new Collection([['foo' => 10], ['foo' => 20]])->min('foo');

// 10

$min = new Collection([1, 2, 3, 4, 5])->min();

// 1

# mode()

The mode method returns the mode value (opens new window) of a given key:

$mode = new Collection([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');

// [10]

$mode = new Collection([1, 1, 2, 4])->mode();

// [1]

# nth()

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

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

$collection->nth(4);

// ['a', 'e']

You may optionally pass an offset as the second argument:

$collection->nth(4, 1);

// ['b', 'f']

# only()

The only method returns the items in the collection with the specified keys:

$collection = new Collection(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']

For the inverse of only, see the except method.

# pad()

The pad method will fill the array with the given value until the array reaches the specified size. This method behaves like the array_pad (opens new window) PHP function.

To pad to the left, you should specify a negative size. No padding will take place if the absolute value of the given size is less than or equal to the length of the array:

$collection = new Collection(['A', 'B', 'C']);

$filtered = $collection->pad(5, 0);

$filtered->all();

// ['A', 'B', 'C', 0, 0]

$filtered = $collection->pad(-5, 0);

$filtered->all();

// [0, 0, 'A', 'B', 'C']

# partition()

The partition method may be combined with the list PHP function to separate elements that pass a given truth test from those that do not:

$collection = new Collection([1, 2, 3, 4, 5, 6]);

list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) {
    return $i < 3;
});

$underThree->all();

// [1, 2]

$equalOrAboveThree->all();

// [3, 4, 5, 6]

# pipe()

The pipe method passes the collection to the given callback and returns the result:

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

$piped = $collection->pipe(function ($collection) {
    return $collection->sum();
});

// 6

# pluck()

The pluck method retrieves all of the collection values for a given key:

$collection = new Collection([
    ['product_id' => 'prod-100', 'name' => 'Chair'],
    ['product_id' => 'prod-200', 'name' => 'Desk'],
]);

$plucked = $collection->pluck('name');

$plucked->all();

// ['Chair', 'Desk']

You may also specify how you wish the resulting collection to be keyed:

$plucked = $collection->pluck('name', 'product_id');

$plucked->all();

// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

# pop()

The pop method removes and returns the last item from the collection:

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

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]

# prepend()

The prepend method adds an item to the beginning of the collection:

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

$collection->prepend(0);

$collection->all();

// [0, 1, 2, 3, 4, 5]

# pull()

The pull method removes and returns an item from the collection by its key:

$collection = new Collection(['product_id' => 'prod-100', 'name' => 'Desk']);

$collection->pull('name');

// 'Desk'

$collection->all();

// ['product_id' => 'prod-100']

# push()

The push method appends an item to the end of the collection:

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

$collection->push(5);

$collection->all();

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

# put()

The put method sets the given key and value in the collection:

$collection = new Collection(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

# random()

The random method returns a random item from the collection:

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

$collection->random();

// 4 - (retrieved randomly)

You may optionally pass an integer to random. If that integer is more than 1, a collection of items is returned:

$random = $collection->random(3);

$random->all();

// [2, 4, 5] - (retrieved randomly)

# reduce()

The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:

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

$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});

// 6

The value for $carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:

$collection->reduce(function ($carry, $item) {
    return $carry + $item;
}, 4);

// 10

# reject()

The reject method filters the collection using the given callback. The callback should return true for any items it wishes to remove from the resulting collection:

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

$filtered = $collection->reject(function ($item) {
    return $item > 2;
});

$filtered->all();

// [1, 2]

For the inverse of the reject method, see the filter method.

# replace()

The replace method behaves similarly to merge; however, in addition to overwriting matching items with string keys, the replace method will also overwrite items in the collection that have matching numeric keys:

$collection = new Collection(['James', 'Scott', 'Dan']);

$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);

$replaced->all();

// ['James', 'Victoria', 'Dan', 'Finn']

# replaceRecursive()

This method works like replace, but it will recur into arrays and apply the same replacement process to the inner values:

$collection = new Collection(['George', 'Scott', ['James', 'Victoria', 'Finn']]);

$replaced = $collection->replaceRecursive(['Charlie', 2 => [1 => 'King']]);

$replaced->all();

// ['Charlie', 'Scott', ['James', 'King', 'Finn']]

# reverse()

The reverse method reverses the order of the collection's items:

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

$reversed = $collection->reverse();

$reversed->all();

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

The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned.

$collection = new Collection([2, 4, 6, 8]);

$collection->search(4);

// 1

The search is done using a "loose" comparison. To use strict comparison, pass true as the second argument to the method:

$collection->search('4', true);

// false

Alternatively, you may pass in your own callback to search for the first item that passes your truth test:

$collection->search(function ($item, $key) {
    return $item > 5;
});

// 2

# shift()

The shift method removes and returns the first item from the collection:

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

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]

# shuffle()

The shuffle method randomly shuffles the items in the collection:

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

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] (generated randomly)

# skip()

The skip method returns a new collection, without the first given amount of items:

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

$collection = $collection->skip(4);

$collection->all();

// [5, 6, 7, 8, 9, 10]

# slice()

The slice method returns a slice of the collection starting at the given index:

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

$slice = $collection->slice(4);

$slice->all();

// [5, 6, 7, 8, 9, 10]

If you would like to limit the size of the returned slice, pass the desired size as the second argument to the method:

$slice = $collection->slice(4, 2);

$slice->all();

// [5, 6]

The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the values method to reindex them.

# some()

Alias for the contains method.

# sort()

The sort method sorts the collection:

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

$sorted = $collection->sort();

$sorted->values()->all();

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

The sorted collection keeps the original array keys. In this example we used the values method to reset the keys to consecutively numbered indexes.

For sorting a collection of nested arrays or objects, see the sortBy and sortByDesc methods.

If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm. Refer to the PHP documentation on usort (opens new window), which is what the collection's sort method calls under the hood.

# sortBy()

The sortBy method sorts the collection by the given key:

$collection = new Collection([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy('price');

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'price' => 100],
        ['name' => 'Bookcase', 'price' => 150],
        ['name' => 'Desk', 'price' => 200],
    ]
*/

The sorted collection keeps the original array keys. In this example we used the values method to reset the keys to consecutively numbered indexes.

You can also pass your own callback to determine how to sort the collection values:

$collection = new Collection([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$sorted = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
});

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
*/

# sortByDesc()

This method has the same signature as the sortBy method, but will sort the collection in the opposite order.

# sortKeys()

The sortKeys method sorts the collection by the keys of the underlying associative array:

$collection = new Collection([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);

$sorted = $collection->sortKeys();

$sorted->all();

/*
    [
        'first' => 'John',
        'id' => 22345,
        'last' => 'Doe',
    ]
*/

# sortKeysDesc()

This method has the same signature as the sortKeys method, but will sort the collection in the opposite order.

# splice()

The splice method removes and returns a slice of items starting at the specified index:

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

$chunk = $collection->splice(2);

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]

You may pass a second argument to limit the size of the resulting chunk:

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

$chunk = $collection->splice(2, 1);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]

In addition, you can pass a third argument containing the new items to replace the items removed from the collection:

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

$chunk = $collection->splice(2, 1, [10, 11]);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 10, 11, 4, 5]

# splice()

The splice method removes and returns a slice of items starting at the specified index:

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

$chunk = $collection->splice(2);

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]

You may pass a second argument to limit the size of the resulting chunk:

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

$chunk = $collection->splice(2, 1);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]

In addition, you can pass a third argument containing the new items to replace the items removed from the collection:

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

$chunk = $collection->splice(2, 1, [10, 11]);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 10, 11, 4, 5]

# split()

The split method breaks a collection into the given number of groups:

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

$groups = $collection->split(3);

$groups->toArray();

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

# sum()

The sum method returns the sum of all items in the collection:

new Collection([1, 2, 3, 4, 5])->sum();

// 15

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

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

$collection->sum('pages');

// 1272

In addition, you may pass your own callback to determine which values of the collection to sum:

$collection = new Collection([
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$collection->sum(function ($product) {
    return count($product['colors']);
});

// 6

# take()

The take method returns a new collection with the specified number of items:

$collection = new Collection([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]

You may also pass a negative integer to take the specified amount of items from the end of the collection:

$collection = new Collection([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(-2);

$chunk->all();

// [4, 5]

# tap()

The tap method passes the collection to the given callback, allowing you to "tap" into the collection at a specific point and do something with the items while not affecting the collection itself:

new Collection([2, 4, 3, 1, 5])
    ->sort()
    ->tap(function ($collection) {
        Log::debug('Values after sorting', $collection->values()->toArray());
    })
    ->shift();

// 1

# times()

The static times method creates a new collection by invoking the callback a given amount of times:

$collection = Collection::times(10, function ($number) {
    return $number * 9;
});

$collection->all();

// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

# toArray()

The toArray method converts the collection into a plain PHP array. If the collection's values are database models, the models will also be converted to arrays:

$collection = new Collection(['name' => 'Desk', 'price' => 200]);

$collection->toArray();

/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/

Note: toArray also converts all of its nested objects to an array. If you want to get the underlying array as is, use the all method instead.

# toJson()

The toJson method converts the collection into JSON:

$collection = new Collection(['name' => 'Desk', 'price' => 200]);

$collection->toJson();

// '{"name":"Desk","price":200}'

# transform()

The transform method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:

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

$collection->transform(function ($item, $key) {
    return $item * 2;
});

$collection->all();

// [2, 4, 6, 8, 10]

Note: Unlike most other collection methods, transform modifies the collection itself. If you wish to create a new collection instead, use the map method.

# union()

The union method adds the given array to the collection. If the given array contains keys that are already in the original collection, the original collection's values will be preferred:

$collection = new Collection([1 => ['a'], 2 => ['b']]);

$union = $collection->union([3 => ['c'], 1 => ['b']]);

$union->all();

// [1 => ['a'], 2 => ['b'], 3 => ['c']]

# unique()

The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:

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

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]

When dealing with nested arrays or objects, you may specify the key used to determine uniqueness:

$collection = new Collection([
    ['name' => 'iPhone 12', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 13', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S21', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);

$unique = $collection->unique('brand');

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 13', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Galaxy S21', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
*/

You may also pass your own callback to determine item uniqueness:

$unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
});

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 12', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S21', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/

The unique method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the uniqueStrict method to filter using "strict" comparisons.

# uniqueStrict()

This method has the same signature as the unique method; however, all values are compared using "strict" comparisons.

# unless()

The unless method will execute the given callback unless the first argument given to the method evaluates to true:

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

$collection->unless(true, function ($collection) {
    return $collection->push(4);
});

$collection->unless(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 5]

For the inverse of unless, see the when method.

# unlessEmpty()

Alias for the whenNotEmpty method.

# unlessNotEmpty()

Alias for the whenEmpty method.

# unwrap()

The static unwrap method returns the collection's underlying items from the given value when applicable:

Collection::unwrap(new Collection('John Doe'));

// ['John Doe']

Collection::unwrap(['John Doe']);

// ['John Doe']

Collection::unwrap('John Doe');

// 'John Doe'

# values()

The values method returns a new collection with the keys reset to consecutive integers:

$collection = new Collection([
    10 => ['product' => 'Desk', 'price' => 200],
    11 => ['product' => 'Desk', 'price' => 200]
]);

$values = $collection->values();

$values->all();

/*
    [
        0 => ['product' => 'Desk', 'price' => 200],
        1 => ['product' => 'Desk', 'price' => 200],
    ]
*/

# when()

The when method will execute the given callback when the first argument given to the method evaluates to true:

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

$collection->when(true, function ($collection) {
    return $collection->push(4);
});

$collection->when(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 4]

For the inverse of when, see the unless method.

# whenEmpty()

The whenEmpty method will execute the given callback when the collection is empty:

$collection = new Collection(['michael', 'tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('steve');
});

$collection->all();

// ['michael', 'tom']


$collection = new Collection();

$collection->whenEmpty(function ($collection) {
    return $collection->push('steve');
});

$collection->all();

// ['steve']

$collection = new Collection(['michael', 'tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('steve');
}, function ($collection) {
    return $collection->push('prince');
});

$collection->all();

// ['michael', 'tom', 'prince']

For the inverse of whenEmpty, see the whenNotEmpty method.

# whenNotEmpty()

The whenNotEmpty method will execute the given callback when the collection is not empty:

$collection = new Collection(['michael', 'tom']);

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('steve');
});

$collection->all();

// ['michael', 'tom', 'steve']


$collection = new Collection();

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('steve');
});

$collection->all();

// []


$collection = new Collection();

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('steve');
}, function ($collection) {
    return $collection->push('prince');
});

$collection->all();

// ['prince']

For the inverse of whenNotEmpty, see the whenEmpty method.

# where()

The where method filters the collection by a given key / value pair:

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

The where method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereStrict method to filter using "strict" comparisons.

Optionally, you may pass a comparison operator as the second parameter.

$collection = new Collection([
    ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
    ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ['name' => 'Sue', 'deleted_at' => null],
]);

$filtered = $collection->where('deleted_at', '!=', null);

$filtered->all();

/*
    [
        ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
        ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ]
*/

# whereStrict()

This method has the same signature as the where method; however, all values are compared using "strict" comparisons.

# whereBetween()

The whereBetween method filters the collection within a given range:

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereBetween('price', [100, 200]);

$filtered->all();

/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
    ]
*/

# whereIn()

The whereIn method filters the collection by a given key / value contained within the given array:

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
    ]
*/

The whereIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereInStrict method to filter using "strict" comparisons.

# whereInStrict()

This method has the same signature as the whereIn method; however, all values are compared using "strict" comparisons.

# whereInstanceOf()

The whereInstanceOf method filters the collection by a given class type:

use App\User;
use App\Post;

$collection = new Collection([
    new User,
    new User,
    new Post,
]);

$filtered = $collection->whereInstanceOf(User::class);

$filtered->all();

// [App\User, App\User]

# whereNotBetween()

The whereNotBetween method filters the collection within a given range:

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereNotBetween('price', [100, 200]);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 80],
        ['product' => 'Pencil', 'price' => 30],
    ]
*/

# whereNotIn()

The whereNotIn method filters the collection by a given key / value not contained within the given array:

$collection = new Collection([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereNotIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

The whereNotIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereNotInStrict method to filter using "strict" comparisons.

# whereNotInStrict()

This method has the same signature as the whereNotIn method; however, all values are compared using "strict" comparisons.

# whereNotNull()

The whereNotNull method filters items where the given key is not null:

$collection = new Collection([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNotNull('name');

$filtered->all();

/*
    [
        ['name' => 'Desk'],
        ['name' => 'Bookcase'],
    ]
*/

# whereNull()

The whereNull method filters items where the given key is null:

$collection = new Collection([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNull('name');

$filtered->all();

/*
    [
        ['name' => null],
    ]
*/

# wrap()

The static wrap method wraps the given value in a collection when applicable:

$collection = Collection::wrap('John Doe');

$collection->all();

// ['John Doe']

$collection = Collection::wrap(['John Doe']);

$collection->all();

// ['John Doe']

$collection = Collection::wrap(new Collection('John Doe'));

$collection->all();

// ['John Doe']

# zip()

The zip method merges together the values of the given array with the values of the original collection at the corresponding index:

$collection = new Collection(['Chair', 'Desk']);

$zipped = $collection->zip([100, 200]);

$zipped->all();

// [['Chair', 100], ['Desk', 200]]