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:

  1. $collection = collect(['taylor', 'abigail', null])->map(function ($name) {
  2. return strtoupper($name);
  3. })
  4. ->reject(function ($name) {
  5. return empty($name);
  6. });

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:

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

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

Extending Collections

Collections are "macroable", which allows you to add additional methods to the Collection class at run time. For example, the following code adds a toUpper method to the Collection class:

  1. use Illuminate\Support\Collection;
  2. use Illuminate\Support\Str;
  3. Collection::macro('toUpper', function () {
  4. return $this->map(function ($value) {
  5. return Str::upper($value);
  6. });
  7. });
  8. $collection = collect(['first', 'second']);
  9. $upper = $collection->toUpper();
  10. // ['FIRST', 'SECOND']

Typically, you should declare collection macros in a service provider.

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 manipulate the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:

allaverageavgchunkcollapsecollectcombineconcatcontainscontainsStrictcountcountBycrossJoindddiffdiffAssocdiffKeysdumpduplicatesduplicatesStricteacheachSpreadeveryexceptfilterfirstfirstWhereflatMapflattenflipforgetforPagegetgroupByhasimplodeintersectintersectByKeysisEmptyisNotEmptyjoinkeyBykeyslastmacromakemapmapIntomapSpreadmapToGroupsmapWithKeysmaxmedianmergemergeRecursiveminmodenthonlypadpartitionpipepluckpopprependpullpushputrandomreducerejectreplacereplaceRecursivereversesearchshiftshuffleskipslicesomesortsortBysortByDescsortDescsortKeyssortKeysDescsplicesplitsumtaketaptimestoArraytoJsontransformunionuniqueuniqueStrictunlessunlessEmptyunlessNotEmptyunwrapvalueswhenwhenEmptywhenNotEmptywherewhereStrictwhereBetweenwhereInwhereInStrictwhereInstanceOfwhereNotBetweenwhereNotInwhereNotInStrictwhereNotNullwhereNullwrapzip

Method Listing

all()

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

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

average()

Alias for the avg method.

avg()

The avg method returns the average value of a given key:

  1. $average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
  2. // 20
  3. $average = collect([1, 1, 2, 4])->avg();
  4. // 2

chunk()

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

  1. $collection = collect([1, 2, 3, 4, 5, 6, 7]);
  2. $chunks = $collection->chunk(4);
  3. $chunks->toArray();
  4. // [[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:

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

collapse()

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

  1. $collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
  2. $collapsed = $collection->collapse();
  3. $collapsed->all();
  4. // [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:

  1. $collection = collect(['name', 'age']);
  2. $combined = $collection->combine(['George', 29]);
  3. $combined->all();
  4. // ['name' => 'George', 'age' => 29]

collect()

The collect method returns a new Collection instance with the items currently in the collection:

  1. $collectionA = collect([1, 2, 3]);
  2. $collectionB = $collectionA->collect();
  3. $collectionB->all();
  4. // [1, 2, 3]

The collect method is primarily useful for converting lazy collections into standard Collection instances:

  1. $lazyCollection = LazyCollection::make(function () {
  2. yield 1;
  3. yield 2;
  4. yield 3;
  5. });
  6. $collection = $lazyCollection->collect();
  7. get_class($collection);
  8. // 'Illuminate\Support\Collection'
  9. $collection->all();
  10. // [1, 2, 3]

{tip} The collect method is especially useful when you have an instance of Enumerable and need a non-lazy collection instance. Since collect() is part of the Enumerable contract, you can safely use it to get a Collection instance.

concat()

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

  1. $collection = collect(['John Doe']);
  2. $concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
  3. $concatenated->all();
  4. // ['John Doe', 'Jane Doe', 'Johnny Doe']

contains()

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

  1. $collection = collect(['name' => 'Desk', 'price' => 100]);
  2. $collection->contains('Desk');
  3. // true
  4. $collection->contains('New York');
  5. // false

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

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 100],
  4. ]);
  5. $collection->contains('product', 'Bookcase');
  6. // false

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

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $collection->contains(function ($value, $key) {
  3. return $value > 5;
  4. });
  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.

{tip} This method's behavior is modified when using Eloquent Collections.

count()

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

  1. $collection = collect([1, 2, 3, 4]);
  2. $collection->count();
  3. // 4

countBy()

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

  1. $collection = collect([1, 2, 2, 2, 3]);
  2. $counted = $collection->countBy();
  3. $counted->all();
  4. // [1 => 1, 2 => 3, 3 => 1]

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

  1. $collection = collect(['[email protected]', '[email protected]', '[email protected]']);
  2. $counted = $collection->countBy(function ($email) {
  3. return substr(strrchr($email, "@"), 1);
  4. });
  5. $counted->all();
  6. // ['gmail.com' => 2, 'yahoo.com' => 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:

  1. $collection = collect([1, 2]);
  2. $matrix = $collection->crossJoin(['a', 'b']);
  3. $matrix->all();
  4. /*
  5. [
  6. [1, 'a'],
  7. [1, 'b'],
  8. [2, 'a'],
  9. [2, 'b'],
  10. ]
  11. */
  12. $collection = collect([1, 2]);
  13. $matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
  14. $matrix->all();
  15. /*
  16. [
  17. [1, 'a', 'I'],
  18. [1, 'a', 'II'],
  19. [1, 'b', 'I'],
  20. [1, 'b', 'II'],
  21. [2, 'a', 'I'],
  22. [2, 'a', 'II'],
  23. [2, 'b', 'I'],
  24. [2, 'b', 'II'],
  25. ]
  26. */

dd()

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

  1. $collection = collect(['John Doe', 'Jane Doe']);
  2. $collection->dd();
  3. /*
  4. Collection {
  5. #items: array:2 [
  6. 0 => "John Doe"
  7. 1 => "Jane Doe"
  8. ]
  9. }
  10. */

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 based on its values. This method will return the values in the original collection that are not present in the given collection:

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $diff = $collection->diff([2, 4, 6, 8]);
  3. $diff->all();
  4. // [1, 3, 5]

{tip} This method's behavior is modified when using Eloquent Collections.

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:

  1. $collection = collect([
  2. 'color' => 'orange',
  3. 'type' => 'fruit',
  4. 'remain' => 6
  5. ]);
  6. $diff = $collection->diffAssoc([
  7. 'color' => 'yellow',
  8. 'type' => 'fruit',
  9. 'remain' => 3,
  10. 'used' => 6,
  11. ]);
  12. $diff->all();
  13. // ['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:

  1. $collection = collect([
  2. 'one' => 10,
  3. 'two' => 20,
  4. 'three' => 30,
  5. 'four' => 40,
  6. 'five' => 50,
  7. ]);
  8. $diff = $collection->diffKeys([
  9. 'two' => 2,
  10. 'four' => 4,
  11. 'six' => 6,
  12. 'eight' => 8,
  13. ]);
  14. $diff->all();
  15. // ['one' => 10, 'three' => 30, 'five' => 50]

dump()

The dump method dumps the collection's items:

  1. $collection = collect(['John Doe', 'Jane Doe']);
  2. $collection->dump();
  3. /*
  4. Collection {
  5. #items: array:2 [
  6. 0 => "John Doe"
  7. 1 => "Jane Doe"
  8. ]
  9. }
  10. */

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:

  1. $collection = collect(['a', 'b', 'a', 'c', 'b']);
  2. $collection->duplicates();
  3. // [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:

  1. $employees = collect([
  2. ['email' => '[email protected]', 'position' => 'Developer'],
  3. ['email' => '[email protected]', 'position' => 'Designer'],
  4. ['email' => '[email protected]', 'position' => 'Developer'],
  5. ])
  6. $employees->duplicates('position');
  7. // [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:

  1. $collection->each(function ($item, $key) {
  2. //
  3. });

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

  1. $collection->each(function ($item, $key) {
  2. if (/* some condition */) {
  3. return false;
  4. }
  5. });

eachSpread()

The eachSpread method iterates over the collection's items, passing each nested item value into the given callback:

  1. $collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
  2. $collection->eachSpread(function ($name, $age) {
  3. //
  4. });

You may stop iterating through the items by returning false from the callback:

  1. $collection->eachSpread(function ($name, $age) {
  2. return false;
  3. });

every()

The every method may be used to verify that all elements of a collection pass a given truth test:

  1. collect([1, 2, 3, 4])->every(function ($value, $key) {
  2. return $value > 2;
  3. });
  4. // false

If the collection is empty, every will return true:

  1. $collection = collect([]);
  2. $collection->every(function ($value, $key) {
  3. return $value > 2;
  4. });
  5. // true

except()

The except method returns all items in the collection except for those with the specified keys:

  1. $collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
  2. $filtered = $collection->except(['price', 'discount']);
  3. $filtered->all();
  4. // ['product_id' => 1]

For the inverse of except, see the only method.

{tip} This method's behavior is modified when using Eloquent Collections.

filter()

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

  1. $collection = collect([1, 2, 3, 4]);
  2. $filtered = $collection->filter(function ($value, $key) {
  3. return $value > 2;
  4. });
  5. $filtered->all();
  6. // [3, 4]

If no callback is supplied, all entries of the collection that are equivalent to false will be removed:

  1. $collection = collect([1, 2, 3, null, false, '', 0, []]);
  2. $collection->filter()->all();
  3. // [1, 2, 3]

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:

  1. collect([1, 2, 3, 4])->first(function ($value, $key) {
  2. return $value > 2;
  3. });
  4. // 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:

  1. collect([1, 2, 3, 4])->first();
  2. // 1

firstWhere()

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

  1. $collection = collect([
  2. ['name' => 'Regena', 'age' => null],
  3. ['name' => 'Linda', 'age' => 14],
  4. ['name' => 'Diego', 'age' => 23],
  5. ['name' => 'Linda', 'age' => 84],
  6. ]);
  7. $collection->firstWhere('name', 'Linda');
  8. // ['name' => 'Linda', 'age' => 14]

You may also call the firstWhere method with an operator:

  1. $collection->firstWhere('age', '>=', 18);
  2. // ['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":

  1. $collection->firstWhere('age');
  2. // ['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:

  1. $collection = collect([
  2. ['name' => 'Sally'],
  3. ['school' => 'Arkansas'],
  4. ['age' => 28]
  5. ]);
  6. $flattened = $collection->flatMap(function ($values) {
  7. return array_map('strtoupper', $values);
  8. });
  9. $flattened->all();
  10. // ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

flatten()

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

  1. $collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
  2. $flattened = $collection->flatten();
  3. $flattened->all();
  4. // ['taylor', 'php', 'javascript'];

You may optionally pass the function a "depth" argument:

  1. $collection = collect([
  2. 'Apple' => [
  3. ['name' => 'iPhone 6S', 'brand' => 'Apple'],
  4. ],
  5. 'Samsung' => [
  6. ['name' => 'Galaxy S7', 'brand' => 'Samsung']
  7. ],
  8. ]);
  9. $products = $collection->flatten(1);
  10. $products->values()->all();
  11. /*
  12. [
  13. ['name' => 'iPhone 6S', 'brand' => 'Apple'],
  14. ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
  15. ]
  16. */

In this example, calling flatten without providing the depth would have also flattened the nested arrays, resulting in ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']. Providing a depth allows you to restrict the levels of nested arrays that will be flattened.

flip()

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

  1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
  2. $flipped = $collection->flip();
  3. $flipped->all();
  4. // ['taylor' => 'name', 'laravel' => 'framework']

forget()

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

  1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
  2. $collection->forget('name');
  3. $collection->all();
  4. // ['framework' => 'laravel']

{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. The method accepts the page number as its first argument and the number of items to show per page as its second argument:

  1. $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  2. $chunk = $collection->forPage(2, 3);
  3. $chunk->all();
  4. // [4, 5, 6]

get()

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

  1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
  2. $value = $collection->get('name');
  3. // taylor

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

  1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
  2. $value = $collection->get('foo', 'default-value');
  3. // 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:

  1. $collection->get('email', function () {
  2. return 'default-value';
  3. });
  4. // default-value

groupBy()

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

  1. $collection = collect([
  2. ['account_id' => 'account-x10', 'product' => 'Chair'],
  3. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
  4. ['account_id' => 'account-x11', 'product' => 'Desk'],
  5. ]);
  6. $grouped = $collection->groupBy('account_id');
  7. $grouped->toArray();
  8. /*
  9. [
  10. 'account-x10' => [
  11. ['account_id' => 'account-x10', 'product' => 'Chair'],
  12. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
  13. ],
  14. 'account-x11' => [
  15. ['account_id' => 'account-x11', 'product' => 'Desk'],
  16. ],
  17. ]
  18. */

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

  1. $grouped = $collection->groupBy(function ($item, $key) {
  2. return substr($item['account_id'], -3);
  3. });
  4. $grouped->toArray();
  5. /*
  6. [
  7. 'x10' => [
  8. ['account_id' => 'account-x10', 'product' => 'Chair'],
  9. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
  10. ],
  11. 'x11' => [
  12. ['account_id' => 'account-x11', 'product' => 'Desk'],
  13. ],
  14. ]
  15. */

Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional array:

  1. $data = new Collection([
  2. 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
  3. 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
  4. 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
  5. 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
  6. ]);
  7. $result = $data->groupBy([
  8. 'skill',
  9. function ($item) {
  10. return $item['roles'];
  11. },
  12. ], $preserveKeys = true);
  13. /*
  14. [
  15. 1 => [
  16. 'Role_1' => [
  17. 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
  18. 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
  19. ],
  20. 'Role_2' => [
  21. 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
  22. ],
  23. 'Role_3' => [
  24. 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
  25. ],
  26. ],
  27. 2 => [
  28. 'Role_1' => [
  29. 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
  30. ],
  31. 'Role_2' => [
  32. 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
  33. ],
  34. ],
  35. ];
  36. */

has()

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

  1. $collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
  2. $collection->has('product');
  3. // true
  4. $collection->has(['product', 'amount']);
  5. // true
  6. $collection->has(['amount', 'price']);
  7. // 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:

  1. $collection = collect([
  2. ['account_id' => 1, 'product' => 'Desk'],
  3. ['account_id' => 2, 'product' => 'Chair'],
  4. ]);
  5. $collection->implode('product', ', ');
  6. // Desk, Chair

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

  1. collect([1, 2, 3, 4, 5])->implode('-');
  2. // '1-2-3-4-5'

intersect()

The intersect method removes any values from the original collection that are not present in the given array or collection. The resulting collection will preserve the original collection's keys:

  1. $collection = collect(['Desk', 'Sofa', 'Chair']);
  2. $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
  3. $intersect->all();
  4. // [0 => 'Desk', 2 => 'Chair']

{tip} This method's behavior is modified when using Eloquent Collections.

intersectByKeys()

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

  1. $collection = collect([
  2. 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
  3. ]);
  4. $intersect = $collection->intersectByKeys([
  5. 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
  6. ]);
  7. $intersect->all();
  8. // ['type' => 'screen', 'year' => 2009]

isEmpty()

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

  1. collect([])->isEmpty();
  2. // true

isNotEmpty()

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

  1. collect([])->isNotEmpty();
  2. // false

join()

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

  1. collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
  2. collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
  3. collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
  4. collect(['a'])->join(', ', ' and '); // 'a'
  5. collect([])->join(', ', ' and '); // ''

keyBy()

The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:

  1. $collection = collect([
  2. ['product_id' => 'prod-100', 'name' => 'Desk'],
  3. ['product_id' => 'prod-200', 'name' => 'Chair'],
  4. ]);
  5. $keyed = $collection->keyBy('product_id');
  6. $keyed->all();
  7. /*
  8. [
  9. 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
  10. 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
  11. ]
  12. */

You may also pass a callback to the method. The callback should return the value to key the collection by:

  1. $keyed = $collection->keyBy(function ($item) {
  2. return strtoupper($item['product_id']);
  3. });
  4. $keyed->all();
  5. /*
  6. [
  7. 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
  8. 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
  9. ]
  10. */

keys()

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

  1. $collection = collect([
  2. 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
  3. 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
  4. ]);
  5. $keys = $collection->keys();
  6. $keys->all();
  7. // ['prod-100', 'prod-200']

last()

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

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

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

  1. collect([1, 2, 3, 4])->last();
  2. // 4

macro()

The static macro method allows you to add methods to the Collection class at run time. Refer to the documentation on extending collections for more information.

make()

The static make method creates a new collection instance. See the Creating Collections section.

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:

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $multiplied = $collection->map(function ($item, $key) {
  3. return $item * 2;
  4. });
  5. $multiplied->all();
  6. // [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:

  1. class Currency
  2. {
  3. /**
  4. * Create a new currency instance.
  5. *
  6. * @param string $code
  7. * @return void
  8. */
  9. function __construct(string $code)
  10. {
  11. $this->code = $code;
  12. }
  13. }
  14. $collection = collect(['USD', 'EUR', 'GBP']);
  15. $currencies = $collection->mapInto(Currency::class);
  16. $currencies->all();
  17. // [Currency('USD'), Currency('EUR'), 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:

  1. $collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  2. $chunks = $collection->chunk(2);
  3. $sequence = $chunks->mapSpread(function ($even, $odd) {
  4. return $even + $odd;
  5. });
  6. $sequence->all();
  7. // [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:

  1. $collection = collect([
  2. [
  3. 'name' => 'John Doe',
  4. 'department' => 'Sales',
  5. ],
  6. [
  7. 'name' => 'Jane Doe',
  8. 'department' => 'Sales',
  9. ],
  10. [
  11. 'name' => 'Johnny Doe',
  12. 'department' => 'Marketing',
  13. ]
  14. ]);
  15. $grouped = $collection->mapToGroups(function ($item, $key) {
  16. return [$item['department'] => $item['name']];
  17. });
  18. $grouped->toArray();
  19. /*
  20. [
  21. 'Sales' => ['John Doe', 'Jane Doe'],
  22. 'Marketing' => ['Johnny Doe'],
  23. ]
  24. */
  25. $grouped->get('Sales')->all();
  26. // ['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:

  1. $collection = collect([
  2. [
  3. 'name' => 'John',
  4. 'department' => 'Sales',
  5. 'email' => '[email protected]'
  6. ],
  7. [
  8. 'name' => 'Jane',
  9. 'department' => 'Marketing',
  10. 'email' => '[email protected]'
  11. ]
  12. ]);
  13. $keyed = $collection->mapWithKeys(function ($item) {
  14. return [$item['email'] => $item['name']];
  15. });
  16. $keyed->all();
  17. /*
  18. [
  19. '[email protected]' => 'John',
  20. '[email protected]' => 'Jane',
  21. ]
  22. */

max()

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

  1. $max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
  2. // 20
  3. $max = collect([1, 2, 3, 4, 5])->max();
  4. // 5

median()

The median method returns the median value of a given key:

  1. $median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
  2. // 15
  3. $median = collect([1, 1, 2, 4])->median();
  4. // 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:

  1. $collection = collect(['product_id' => 1, 'price' => 100]);
  2. $merged = $collection->merge(['price' => 200, 'discount' => false]);
  3. $merged->all();
  4. // ['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:

  1. $collection = collect(['Desk', 'Chair']);
  2. $merged = $collection->merge(['Bookcase', 'Door']);
  3. $merged->all();
  4. // ['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:

  1. $collection = collect(['product_id' => 1, 'price' => 100]);
  2. $merged = $collection->mergeRecursive(['product_id' => 2, 'price' => 200, 'discount' => false]);
  3. $merged->all();
  4. // ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]

min()

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

  1. $min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
  2. // 10
  3. $min = collect([1, 2, 3, 4, 5])->min();
  4. // 1

mode()

The mode method returns the mode value) of a given key:

  1. $mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
  2. // [10]
  3. $mode = collect([1, 1, 2, 4])->mode();
  4. // [1]

nth()

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

  1. $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
  2. $collection->nth(4);
  3. // ['a', 'e']

You may optionally pass an offset as the second argument:

  1. $collection->nth(4, 1);
  2. // ['b', 'f']

only()

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

  1. $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
  2. $filtered = $collection->only(['product_id', 'name']);
  3. $filtered->all();
  4. // ['product_id' => 1, 'name' => 'Desk']

For the inverse of only, see the except method.

{tip} This method's behavior is modified when using Eloquent Collections.

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 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:

  1. $collection = collect(['A', 'B', 'C']);
  2. $filtered = $collection->pad(5, 0);
  3. $filtered->all();
  4. // ['A', 'B', 'C', 0, 0]
  5. $filtered = $collection->pad(-5, 0);
  6. $filtered->all();
  7. // [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:

  1. $collection = collect([1, 2, 3, 4, 5, 6]);
  2. list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) {
  3. return $i < 3;
  4. });
  5. $underThree->all();
  6. // [1, 2]
  7. $equalOrAboveThree->all();
  8. // [3, 4, 5, 6]

pipe()

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

  1. $collection = collect([1, 2, 3]);
  2. $piped = $collection->pipe(function ($collection) {
  3. return $collection->sum();
  4. });
  5. // 6

pluck()

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

  1. $collection = collect([
  2. ['product_id' => 'prod-100', 'name' => 'Desk'],
  3. ['product_id' => 'prod-200', 'name' => 'Chair'],
  4. ]);
  5. $plucked = $collection->pluck('name');
  6. $plucked->all();
  7. // ['Desk', 'Chair']

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

  1. $plucked = $collection->pluck('name', 'product_id');
  2. $plucked->all();
  3. // ['prod-100' => 'Desk', 'prod-200' => 'Chair']

If duplicate keys exist, the last matching element will be inserted into the plucked collection:

  1. $collection = collect([
  2. ['brand' => 'Tesla', 'color' => 'red'],
  3. ['brand' => 'Pagani', 'color' => 'white'],
  4. ['brand' => 'Tesla', 'color' => 'black'],
  5. ['brand' => 'Pagani', 'color' => 'orange'],
  6. ]);
  7. $plucked = $collection->pluck('color', 'brand');
  8. $plucked->all();
  9. // ['Tesla' => 'black', 'Pagani' => 'orange']

pop()

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

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $collection->pop();
  3. // 5
  4. $collection->all();
  5. // [1, 2, 3, 4]

prepend()

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

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $collection->prepend(0);
  3. $collection->all();
  4. // [0, 1, 2, 3, 4, 5]

You may also pass a second argument to set the key of the prepended item:

  1. $collection = collect(['one' => 1, 'two' => 2]);
  2. $collection->prepend(0, 'zero');
  3. $collection->all();
  4. // ['zero' => 0, 'one' => 1, 'two' => 2]

pull()

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

  1. $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
  2. $collection->pull('name');
  3. // 'Desk'
  4. $collection->all();
  5. // ['product_id' => 'prod-100']

push()

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

  1. $collection = collect([1, 2, 3, 4]);
  2. $collection->push(5);
  3. $collection->all();
  4. // [1, 2, 3, 4, 5]

put()

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

  1. $collection = collect(['product_id' => 1, 'name' => 'Desk']);
  2. $collection->put('price', 100);
  3. $collection->all();
  4. // ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

random()

The random method returns a random item from the collection:

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $collection->random();
  3. // 4 - (retrieved randomly)

You may optionally pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:

  1. $random = $collection->random(3);
  2. $random->all();
  3. // [2, 4, 5] - (retrieved randomly)

If the Collection has fewer items than requested, the method will throw an InvalidArgumentException.

reduce()

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

  1. $collection = collect([1, 2, 3]);
  2. $total = $collection->reduce(function ($carry, $item) {
  3. return $carry + $item;
  4. });
  5. // 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:

  1. $collection->reduce(function ($carry, $item) {
  2. return $carry + $item;
  3. }, 4);
  4. // 10

reject()

The reject method filters the collection using the given callback. The callback should return true if the item should be removed from the resulting collection:

  1. $collection = collect([1, 2, 3, 4]);
  2. $filtered = $collection->reject(function ($value, $key) {
  3. return $value > 2;
  4. });
  5. $filtered->all();
  6. // [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:

  1. $collection = collect(['Taylor', 'Abigail', 'James']);
  2. $replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);
  3. $replaced->all();
  4. // ['Taylor', 'Victoria', 'James', 'Finn']

replaceRecursive()

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

  1. $collection = collect(['Taylor', 'Abigail', ['James', 'Victoria', 'Finn']]);
  2. $replaced = $collection->replaceRecursive(['Charlie', 2 => [1 => 'King']]);
  3. $replaced->all();
  4. // ['Charlie', 'Abigail', ['James', 'King', 'Finn']]

reverse()

The reverse method reverses the order of the collection's items, preserving the original keys:

  1. $collection = collect(['a', 'b', 'c', 'd', 'e']);
  2. $reversed = $collection->reverse();
  3. $reversed->all();
  4. /*
  5. [
  6. 4 => 'e',
  7. 3 => 'd',
  8. 2 => 'c',
  9. 1 => 'b',
  10. 0 => 'a',
  11. ]
  12. */

search()

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.

  1. $collection = collect([2, 4, 6, 8]);
  2. $collection->search(4);
  3. // 1

The search is done using a "loose" comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use "strict" comparison, pass true as the second argument to the method:

  1. $collection->search('4', true);
  2. // false

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

  1. $collection->search(function ($item, $key) {
  2. return $item > 5;
  3. });
  4. // 2

shift()

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

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $collection->shift();
  3. // 1
  4. $collection->all();
  5. // [2, 3, 4, 5]

shuffle()

The shuffle method randomly shuffles the items in the collection:

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $shuffled = $collection->shuffle();
  3. $shuffled->all();
  4. // [3, 2, 5, 1, 4] - (generated randomly)

skip()

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

  1. $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
  2. $collection = $collection->skip(4);
  3. $collection->all();
  4. // [5, 6, 7, 8, 9, 10]

slice()

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

  1. $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
  2. $slice = $collection->slice(4);
  3. $slice->all();
  4. // [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:

  1. $slice = $collection->slice(4, 2);
  2. $slice->all();
  3. // [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. The sorted collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:

  1. $collection = collect([5, 3, 1, 2, 4]);
  2. $sorted = $collection->sort();
  3. $sorted->values()->all();
  4. // [1, 2, 3, 4, 5]

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

{tip} If you need to sort a collection of nested arrays or objects, see the sortBy and sortByDesc methods.

sortBy()

The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:

  1. $collection = collect([
  2. ['name' => 'Desk', 'price' => 200],
  3. ['name' => 'Chair', 'price' => 100],
  4. ['name' => 'Bookcase', 'price' => 150],
  5. ]);
  6. $sorted = $collection->sortBy('price');
  7. $sorted->values()->all();
  8. /*
  9. [
  10. ['name' => 'Chair', 'price' => 100],
  11. ['name' => 'Bookcase', 'price' => 150],
  12. ['name' => 'Desk', 'price' => 200],
  13. ]
  14. */

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

  1. $collection = collect([
  2. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
  3. ['name' => 'Chair', 'colors' => ['Black']],
  4. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
  5. ]);
  6. $sorted = $collection->sortBy(function ($product, $key) {
  7. return count($product['colors']);
  8. });
  9. $sorted->values()->all();
  10. /*
  11. [
  12. ['name' => 'Chair', 'colors' => ['Black']],
  13. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
  14. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
  15. ]
  16. */

sortByDesc()

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

sortDesc()

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

  1. $collection = collect([5, 3, 1, 2, 4]);
  2. $sorted = $collection->sortDesc();
  3. $sorted->values()->all();
  4. // [5, 4, 3, 2, 1]

sortKeys()

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

  1. $collection = collect([
  2. 'id' => 22345,
  3. 'first' => 'John',
  4. 'last' => 'Doe',
  5. ]);
  6. $sorted = $collection->sortKeys();
  7. $sorted->all();
  8. /*
  9. [
  10. 'first' => 'John',
  11. 'id' => 22345,
  12. 'last' => 'Doe',
  13. ]
  14. */

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:

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $chunk = $collection->splice(2);
  3. $chunk->all();
  4. // [3, 4, 5]
  5. $collection->all();
  6. // [1, 2]

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

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $chunk = $collection->splice(2, 1);
  3. $chunk->all();
  4. // [3]
  5. $collection->all();
  6. // [1, 2, 4, 5]

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

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $chunk = $collection->splice(2, 1, [10, 11]);
  3. $chunk->all();
  4. // [3]
  5. $collection->all();
  6. // [1, 2, 10, 11, 4, 5]

split()

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

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $groups = $collection->split(3);
  3. $groups->toArray();
  4. // [[1, 2], [3, 4], [5]]

sum()

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

  1. collect([1, 2, 3, 4, 5])->sum();
  2. // 15

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

  1. $collection = collect([
  2. ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
  3. ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
  4. ]);
  5. $collection->sum('pages');
  6. // 1272

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

  1. $collection = collect([
  2. ['name' => 'Chair', 'colors' => ['Black']],
  3. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
  4. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
  5. ]);
  6. $collection->sum(function ($product) {
  7. return count($product['colors']);
  8. });
  9. // 6

take()

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

  1. $collection = collect([0, 1, 2, 3, 4, 5]);
  2. $chunk = $collection->take(3);
  3. $chunk->all();
  4. // [0, 1, 2]

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

  1. $collection = collect([0, 1, 2, 3, 4, 5]);
  2. $chunk = $collection->take(-2);
  3. $chunk->all();
  4. // [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:

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

times()

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

  1. $collection = Collection::times(10, function ($number) {
  2. return $number * 9;
  3. });
  4. $collection->all();
  5. // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

This method can be useful when combined with factories to create Eloquent models:

  1. $categories = Collection::times(3, function ($number) {
  2. return factory(Category::class)->create(['name' => "Category No. $number"]);
  3. });
  4. $categories->all();
  5. /*
  6. [
  7. ['id' => 1, 'name' => 'Category No. 1'],
  8. ['id' => 2, 'name' => 'Category No. 2'],
  9. ['id' => 3, 'name' => 'Category No. 3'],
  10. ]
  11. */

toArray()

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

  1. $collection = collect(['name' => 'Desk', 'price' => 200]);
  2. $collection->toArray();
  3. /*
  4. [
  5. ['name' => 'Desk', 'price' => 200],
  6. ]
  7. */

{note} toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.

toJson()

The toJson method converts the collection into a JSON serialized string:

  1. $collection = collect(['name' => 'Desk', 'price' => 200]);
  2. $collection->toJson();
  3. // '{"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:

  1. $collection = collect([1, 2, 3, 4, 5]);
  2. $collection->transform(function ($item, $key) {
  3. return $item * 2;
  4. });
  5. $collection->all();
  6. // [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:

  1. $collection = collect([1 => ['a'], 2 => ['b']]);
  2. $union = $collection->union([3 => ['c'], 1 => ['b']]);
  3. $union->all();
  4. // [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:

  1. $collection = collect([1, 1, 2, 2, 3, 4, 2]);
  2. $unique = $collection->unique();
  3. $unique->values()->all();
  4. // [1, 2, 3, 4]

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

  1. $collection = collect([
  2. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
  3. ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
  4. ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
  5. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
  6. ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
  7. ]);
  8. $unique = $collection->unique('brand');
  9. $unique->values()->all();
  10. /*
  11. [
  12. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
  13. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
  14. ]
  15. */

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

  1. $unique = $collection->unique(function ($item) {
  2. return $item['brand'].$item['type'];
  3. });
  4. $unique->values()->all();
  5. /*
  6. [
  7. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
  8. ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
  9. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
  10. ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
  11. ]
  12. */

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.

{tip} This method's behavior is modified when using Eloquent Collections.

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:

  1. $collection = collect([1, 2, 3]);
  2. $collection->unless(true, function ($collection) {
  3. return $collection->push(4);
  4. });
  5. $collection->unless(false, function ($collection) {
  6. return $collection->push(5);
  7. });
  8. $collection->all();
  9. // [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:

  1. Collection::unwrap(collect('John Doe'));
  2. // ['John Doe']
  3. Collection::unwrap(['John Doe']);
  4. // ['John Doe']
  5. Collection::unwrap('John Doe');
  6. // 'John Doe'

values()

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

  1. $collection = collect([
  2. 10 => ['product' => 'Desk', 'price' => 200],
  3. 11 => ['product' => 'Desk', 'price' => 200]
  4. ]);
  5. $values = $collection->values();
  6. $values->all();
  7. /*
  8. [
  9. 0 => ['product' => 'Desk', 'price' => 200],
  10. 1 => ['product' => 'Desk', 'price' => 200],
  11. ]
  12. */

when()

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

  1. $collection = collect([1, 2, 3]);
  2. $collection->when(true, function ($collection) {
  3. return $collection->push(4);
  4. });
  5. $collection->when(false, function ($collection) {
  6. return $collection->push(5);
  7. });
  8. $collection->all();
  9. // [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:

  1. $collection = collect(['michael', 'tom']);
  2. $collection->whenEmpty(function ($collection) {
  3. return $collection->push('adam');
  4. });
  5. $collection->all();
  6. // ['michael', 'tom']
  7. $collection = collect();
  8. $collection->whenEmpty(function ($collection) {
  9. return $collection->push('adam');
  10. });
  11. $collection->all();
  12. // ['adam']
  13. $collection = collect(['michael', 'tom']);
  14. $collection->whenEmpty(function ($collection) {
  15. return $collection->push('adam');
  16. }, function ($collection) {
  17. return $collection->push('taylor');
  18. });
  19. $collection->all();
  20. // ['michael', 'tom', 'taylor']

For the inverse of whenEmpty, see the whenNotEmpty method.

whenNotEmpty()

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

  1. $collection = collect(['michael', 'tom']);
  2. $collection->whenNotEmpty(function ($collection) {
  3. return $collection->push('adam');
  4. });
  5. $collection->all();
  6. // ['michael', 'tom', 'adam']
  7. $collection = collect();
  8. $collection->whenNotEmpty(function ($collection) {
  9. return $collection->push('adam');
  10. });
  11. $collection->all();
  12. // []
  13. $collection = collect();
  14. $collection->whenNotEmpty(function ($collection) {
  15. return $collection->push('adam');
  16. }, function ($collection) {
  17. return $collection->push('taylor');
  18. });
  19. $collection->all();
  20. // ['taylor']

For the inverse of whenNotEmpty, see the whenEmpty method.

where()

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

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 100],
  4. ['product' => 'Bookcase', 'price' => 150],
  5. ['product' => 'Door', 'price' => 100],
  6. ]);
  7. $filtered = $collection->where('price', 100);
  8. $filtered->all();
  9. /*
  10. [
  11. ['product' => 'Chair', 'price' => 100],
  12. ['product' => 'Door', 'price' => 100],
  13. ]
  14. */

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.

  1. $collection = collect([
  2. ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
  3. ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
  4. ['name' => 'Sue', 'deleted_at' => null],
  5. ]);
  6. $filtered = $collection->where('deleted_at', '!=', null);
  7. $filtered->all();
  8. /*
  9. [
  10. ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
  11. ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
  12. ]
  13. */

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:

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 80],
  4. ['product' => 'Bookcase', 'price' => 150],
  5. ['product' => 'Pencil', 'price' => 30],
  6. ['product' => 'Door', 'price' => 100],
  7. ]);
  8. $filtered = $collection->whereBetween('price', [100, 200]);
  9. $filtered->all();
  10. /*
  11. [
  12. ['product' => 'Desk', 'price' => 200],
  13. ['product' => 'Bookcase', 'price' => 150],
  14. ['product' => 'Door', 'price' => 100],
  15. ]
  16. */

whereIn()

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

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 100],
  4. ['product' => 'Bookcase', 'price' => 150],
  5. ['product' => 'Door', 'price' => 100],
  6. ]);
  7. $filtered = $collection->whereIn('price', [150, 200]);
  8. $filtered->all();
  9. /*
  10. [
  11. ['product' => 'Desk', 'price' => 200],
  12. ['product' => 'Bookcase', 'price' => 150],
  13. ]
  14. */

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:

  1. use App\User;
  2. use App\Post;
  3. $collection = collect([
  4. new User,
  5. new User,
  6. new Post,
  7. ]);
  8. $filtered = $collection->whereInstanceOf(User::class);
  9. $filtered->all();
  10. // [App\User, App\User]

whereNotBetween()

The whereNotBetween method filters the collection within a given range:

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 80],
  4. ['product' => 'Bookcase', 'price' => 150],
  5. ['product' => 'Pencil', 'price' => 30],
  6. ['product' => 'Door', 'price' => 100],
  7. ]);
  8. $filtered = $collection->whereNotBetween('price', [100, 200]);
  9. $filtered->all();
  10. /*
  11. [
  12. ['product' => 'Chair', 'price' => 80],
  13. ['product' => 'Pencil', 'price' => 30],
  14. ]
  15. */

whereNotIn()

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

  1. $collection = collect([
  2. ['product' => 'Desk', 'price' => 200],
  3. ['product' => 'Chair', 'price' => 100],
  4. ['product' => 'Bookcase', 'price' => 150],
  5. ['product' => 'Door', 'price' => 100],
  6. ]);
  7. $filtered = $collection->whereNotIn('price', [150, 200]);
  8. $filtered->all();
  9. /*
  10. [
  11. ['product' => 'Chair', 'price' => 100],
  12. ['product' => 'Door', 'price' => 100],
  13. ]
  14. */

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:

  1. $collection = collect([
  2. ['name' => 'Desk'],
  3. ['name' => null],
  4. ['name' => 'Bookcase'],
  5. ]);
  6. $filtered = $collection->whereNotNull('name');
  7. $filtered->all();
  8. /*
  9. [
  10. ['name' => 'Desk'],
  11. ['name' => 'Bookcase'],
  12. ]
  13. */

whereNull()

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

  1. $collection = collect([
  2. ['name' => 'Desk'],
  3. ['name' => null],
  4. ['name' => 'Bookcase'],
  5. ]);
  6. $filtered = $collection->whereNull('name');
  7. $filtered->all();
  8. /*
  9. [
  10. ['name' => null],
  11. ]
  12. */

wrap()

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

  1. $collection = Collection::wrap('John Doe');
  2. $collection->all();
  3. // ['John Doe']
  4. $collection = Collection::wrap(['John Doe']);
  5. $collection->all();
  6. // ['John Doe']
  7. $collection = Collection::wrap(collect('John Doe'));
  8. $collection->all();
  9. // ['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:

  1. $collection = collect(['Chair', 'Desk']);
  2. $zipped = $collection->zip([100, 200]);
  3. $zipped->all();
  4. // [['Chair', 100], ['Desk', 200]]

Higher Order Messages

Collections also provide support for "higher order messages", which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: average, avg, contains, each, every, filter, first, flatMap, groupBy, keyBy, map, max, min, partition, reject, some, sortBy, sortByDesc, sum, and unique.

Each higher order message can be accessed as a dynamic property on a collection instance. For instance, let's use the each higher order message to call a method on each object within a collection:

  1. $users = User::where('votes', '>', 500)->get();
  2. $users->each->markAsVip();

Likewise, we can use the sum higher order message to gather the total number of "votes" for a collection of users:

  1. $users = User::where('group', 'Development')->get();
  2. return $users->sum->votes;

Lazy Collections

Introduction

{note} Before learning more about Laravel's lazy collections, take some time to familiarize yourself with PHP generators.

To supplement the already powerful Collection class, the LazyCollection class leverages PHP's generators to allow you to work with very large datasets while keeping memory usage low.

For example, imagine your application needs to process a multi-gigabyte log file while taking advantage of Laravel's collection methods to parse the logs. Instead of reading the entire file into memory at once, lazy collections may be used to keep only a small part of the file in memory at a given time:

  1. use App\LogEntry;
  2. use Illuminate\Support\LazyCollection;
  3. LazyCollection::make(function () {
  4. $handle = fopen('log.txt', 'r');
  5. while (($line = fgets($handle)) !== false) {
  6. yield $line;
  7. }
  8. })->chunk(4)->map(function ($lines) {
  9. return LogEntry::fromLines($lines);
  10. })->each(function (LogEntry $logEntry) {
  11. // Process the log entry...
  12. });

Or, imagine you need to iterate through 10,000 Eloquent models. When using traditional Laravel collections, all 10,000 Eloquent models must be loaded into memory at the same time:

  1. $users = App\User::all()->filter(function ($user) {
  2. return $user->id > 500;
  3. });

However, the query builder's cursor method returns a LazyCollection instance. This allows you to still only run a single query against the database but also only keep one Eloquent model loaded in memory at a time. In this example, the filter callback is not executed until we actually iterate over each user individually, allowing for a drastic reduction in memory usage:

  1. $users = App\User::cursor()->filter(function ($user) {
  2. return $user->id > 500;
  3. });
  4. foreach ($users as $user) {
  5. echo $user->id;
  6. }

Creating Lazy Collections

To create a lazy collection instance, you should pass a PHP generator function to the collection's make method:

  1. use Illuminate\Support\LazyCollection;
  2. LazyCollection::make(function () {
  3. $handle = fopen('log.txt', 'r');
  4. while (($line = fgets($handle)) !== false) {
  5. yield $line;
  6. }
  7. });

The Enumerable Contract

Almost all methods available on the Collection class are also available on the LazyCollection class. Both of these classes implement the Illuminate\Support\Enumerable contract, which defines the following methods:

allaverageavgchunkcollapsecollectcombineconcatcontainscontainsStrictcountcountBycrossJoindddiffdiffAssocdiffKeysdumpduplicatesduplicatesStricteacheachSpreadeveryexceptfilterfirstfirstWhereflatMapflattenflipforPagegetgroupByhasimplodeintersectintersectByKeysisEmptyisNotEmptyjoinkeyBykeyslastmacromakemapmapIntomapSpreadmapToGroupsmapWithKeysmaxmedianmergemergeRecursiveminmodenthonlypadpartitionpipepluckrandomreducerejectreplacereplaceRecursivereversesearchshuffleskipslicesomesortsortBysortByDescsortKeyssortKeysDescsplitsumtaketaptimestoArraytoJsonunionuniqueuniqueStrictunlessunlessEmptyunlessNotEmptyunwrapvalueswhenwhenEmptywhenNotEmptywherewhereStrictwhereBetweenwhereInwhereInStrictwhereInstanceOfwhereNotBetweenwhereNotInwhereNotInStrictwrapzip

{note} Methods that mutate the collection (such as shift, pop, prepend etc.) are not available on the LazyCollection class.

Lazy Collection Methods

In addition to the methods defined in the Enumerable contract, the LazyCollection class contains the following methods:

tapEach()

While the each method calls the given callback for each item in the collection right away, the tapEach method only calls the given callback as the items are being pulled out of the list one by one:

  1. $lazyCollection = LazyCollection::times(INF)->tapEach(function ($value) {
  2. dump($value);
  3. });
  4. // Nothing has been dumped so far...
  5. $array = $lazyCollection->take(3)->all();
  6. // 1
  7. // 2
  8. // 3

remember()

The remember method returns a new lazy collection that will remember any values that have already been enumerated and will not retrieve them again when the collection is enumerated again:

  1. $users = User::cursor()->remember();
  2. // No query has been executed yet...
  3. $users->take(5)->all();
  4. // The query has been executed and the first 5 users have been hydrated from the database...
  5. $users->take(20)->all();
  6. // First 5 users come from the collection's cache... The rest are hydrated from the database...