Collection: add wings to PHP arrays


brief introduction

Illuminate\Support\Collection Class provides streaming and convenient encapsulation for processing array data. For example, looking at the following code, we use auxiliary functions collect Create a new collection instance and run it for each element strtoupper Function, and then remove all empty elements:

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

As you can see, Collection Class allows you to use the method chain to perform matching and removal operations on the underlying array. Usually, each Collection Method will return a new Collection example.

Create Collection

As mentioned above, auxiliary functions collect Returns a new Illuminate\Support\Collection Therefore, creating a collection is simple:

 $collection = collect([1, 2, 3]);
Note: By default, Eloquent The query result is always returned Collection example.

Extended Collection

The collection is "macro", which means that we can dynamically add methods to Collection Class, for example, the following code adds toUpper Method to Collection Class:

 use Illuminate\Support\Str; Collection::macro('toUpper', function () { return $this->map(function ($value) { return Str::upper($value); }); }); $collection = collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND']

Usually, we need to Service Provider Collection macros are declared in.

Set method

The next part of this document will introduce Collection For each valid method on the class, all these methods can stream the underlying array in the way of method chain. In addition, almost every method returns a new Collection Instance, which allows you to keep the original collection backup when necessary.

Method List

all()

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

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

avg()

avg Method returns the average value of all collection items:

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

average()

avg Alias of the method.

chunk()

chunk Method To divide a set into multiple small sets of small size:

 $collection = collect([1, 2, 3, 4, 5, 6, 7]); $chunks = $collection->chunk(4); $chunks->toArray(); // [[1, 2, 3, 4], [5, 6, 7]]

When dealing with fence systems such as Bootstrap When the method is view It is especially useful to build a Eloquent Model collection:

 @foreach ($products->chunk(3) as $chunk)
@foreach ($chunk as $product)
{{ $product->name }}
@endforeach
@endforeach

collapse()

collapse Method to shrink a multidimensional array collection into a one-dimensional array:

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

combine()

combine Method can connect the key of one collection with the value of another array or collection:

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

concat()

concat Method can be used to append the given array or collection data to the end of the collection:

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

contains()

contains Method to determine whether a set contains a given item:

 $collection = collect(['name' => 'Desk', 'price' => 100]); $collection->contains('Desk'); // true $collection->contains('New York'); // false

You can also pass a key value pair to contains Method, which will determine whether the given key value pair exists in the collection:

 $collection = collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ]); $collection->contains('product', 'Bookcase'); // false

Finally, you can also send a callback to contains Method to perform your own real-world tests:

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

contains Method uses "loose" comparison when checking values, which means that a string containing an integer value is equal to the same integer value (for example, '1' and one Equal). To make a strict comparison, you can use containsStrict method.

containsStrict()

This method and contains Method signatures are the same, but all values are strictly compared.

count()

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

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

crossJoin()

crossJoin Method will cross combine the set values between the given array or set, and then return the Cartesian product of all possible permutations and combinations:

 $collection = collect([1, 2]); $matrix = $collection->crossJoin(['a', 'b']); $matrix->all(); /* [ [1, 'a'], [1, 'b'], [2, 'a'], [2, 'b'], ] */ $collection = collect([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()

dd Method prints the collection item and ends script execution:

 $collection = collect(['John Doe', 'Jane Doe']); $collection->dd(); /* Collection { #items: array:2 [ 0 => "John Doe" 1 => "Jane Doe" ] } */

If you do not want to terminate script execution, you can use dump Method.

dump()

dump Method prints the collection items without terminating script execution:

 $collection = collect(['John Doe', 'Jane Doe']); $collection->dump(); /* Collection { #items: array:2 [ 0 => "John Doe" 1 => "Jane Doe" ] } */

If you want to terminate script execution after printing the collection, you can use dd Method.

diff()

diff Method compares a set with another set or a native PHP array in a value based way. This method returns the values that exist in the original set but not in the given set:

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

diffAssoc()

diffAssoc Method compares one collection with another or a native PHP array based on key values. This method returns key value pairs that only exist in the first collection:

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

diffKeys()

diffKeys Method will compare a collection with another collection or a native PHP array based on Qian. This method will return key value pairs that only exist in the first collection:

 $collection = collect([ '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]

each()

each Method iterates over data items in the collection and passes each data item to the given callback:

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

If you want to terminate the iteration of the data item, you can return from the callback false

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

eachSpread()

eachSpread The method will iterate over the collection items, passing each nested data item value to the given collection:

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

You can return false To stop the iteration of the collection item:

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

every()

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

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

except()

except Method returns all collection items in the collection except the specified key:

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

And except In contrast only method.

filter()

filter The method filters the collection through a given callback. Only data items that pass a given truth test will remain:

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

If no callback is provided, then all in the collection are equivalent to false 's items will be removed:

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

and filter The relative method is reject

first()

first The method returns the first element of the truth test set:

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

You can also call the first Method to get the first element of the collection. If the collection is empty, return null

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

firstWhere()

firstWhere Method will return the first element in the collection, including key value pairs:

 $collection = collect([ ['name' => 'Regena', 'age' => 12], ['name' => 'Linda', 'age' => 14], ['name' => 'Diego', 'age' => 23], ['name' => 'Linda', 'age' => 84], ]); $collection->firstWhere('name', 'Linda'); // ['name' => 'Linda', 'age' => 14]

You can also call the firstWhere method:

 $collection->firstWhere('age', '>=', 18); // ['name' => 'Diego', 'age' => 23]

flatMap()

flatMap The method iterates over the collection and passes each value to the given callback, which can freely edit the data item and return it to form a new edited collection. Then, the array is flattened in the hierarchical dimension:

 $collection = collect([ ['name' => 'Sally'], ['school' => 'Arkansas'], ['age' => 28] ]); $flattened = $collection->flatMap(function ($values) { return array_map('strtoupper', $values); }); $flattened->all(); // ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

flatten()

flatten The method changes a multi-dimensional set into a one-dimensional set:

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

You can also optionally pass in depth parameters:

 $collection = collect([ 'Apple' => [ ['name' => 'iPhone 6S', 'brand' => 'Apple'], ], 'Samsung' => [ ['name' => 'Galaxy S7', 'brand' => 'Samsung'] ], ]); $products = $collection->flatten(1); $products->values()->all(); /* [ ['name' => 'iPhone 6S', 'brand' => 'Apple'], ['name' => 'Galaxy S7', 'brand' => 'Samsung'], ] */

In this case, call the flatten Method will also flatten the nested array, and the return result is ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung'] Providing depth allows you to strictly set the array level to be flattened.

flip()

flip Method to exchange the key values of the collection:

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

forget()

forget Method to remove data items from a collection by key:

 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $collection->forget('name'); $collection->all(); // [framework' => 'laravel']
Note: Unlike most other set methods, forget Do not return the new modified set; It only modifies the called collection.
forPage()

forPage Method returns a new collection containing data items for the given number of pages. This method receives the number of page numbers as the first parameter, and displays the number of data items per page as the second parameter:

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

get()

get Method returns the data item of the given key. If the corresponding key does not exist, it returns null

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

You can choose to pass the default value as the second parameter:

 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('foo', 'default-value'); // default-value

You can even pass a callback as the default value. If the given key does not exist, the callback result will return:

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

groupBy()

groupBy Method to group collection data items by given key:

 $collection = collect([ ['account_id' => 'account-x10', 'product' => 'Chair'], ['account_id' => 'account-x10', 'product' => 'Bookcase'], ['account_id' => 'account-x11', 'product' => 'Desk'], ]); $grouped = $collection->groupBy('account_id'); $grouped->toArray(); /* [ 'account-x10' => [ ['account_id' => 'account-x10', 'product' => 'Chair'], ['account_id' => 'account-x10', 'product' => 'Bookcase'], ], 'account-x11' => [ ['account_id' => 'account-x11', 'product' => 'Desk'], ], ] */

In addition to passing strings key , you can also pass a callback, which should return the grouped value:

 $grouped = $collection->groupBy(function ($item, $key) { return substr($item['account_id'], -3); }); $grouped->toArray(); /* [ 'x10' => [ ['account_id' => 'account-x10', 'product' => 'Chair'], ['account_id' => 'account-x10', 'product' => 'Bookcase'], ], 'x11' => [ ['account_id' => 'account-x11', 'product' => 'Desk'], ], ] */

Multiple grouping conditions can be passed in an array, and each array element will be applied to the corresponding level in the multidimensional array:

 $data = new Collection([ 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']], 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']], ]); $result = $data->groupBy([ 'skill', function ($item) { return $item['roles']; }, ], $preserveKeys = true); /* [ 1 => [ 'Role_1' => [ 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], ], 'Role_2' => [ 20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']], ], 'Role_3' => [ 10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']], ], ], 2 => [ 'Role_1' => [ 30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']], ], 'Role_2' => [ 40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']], ], ], ]; */

has()

has Method to determine whether the given key exists in the set:

 $collection = collect(['account_id' => 1, 'product' => 'Desk']); $collection->has('email'); // false

implode()

implode Method to connect data items in a collection. Its parameters depend on the type of data item in the collection. If the collection contains arrays or objects, you should pass the attribute keys you want to connect and the "glue" string you want to put between values:

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

If the collection contains a simple string or numeric value, just pass the "glue" string as the only parameter to the method:

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

intersect()

intersect Method returns the intersection of two sets, and the result set will retain the key of the original set:

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

intersectByKeys()

intersectByKeys Method will remove any key that does not appear in the given array or collection from the native collection:

 $collection = collect([ 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009 ]); $intersect = $collection->intersectByKeys([ 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011 ]); $intersect->all(); // ['type' => 'screen', 'year' => 2009]

isEmpty()

If the collection is empty isEmpty Method return true Otherwise, return false

 collect([])->isEmpty(); // true

isNotEmpty()

If the collection is not empty isNotEmpty Method return true Otherwise, return false

 collect([])->isNotEmpty(); // false

keyBy()

keyBy Method takes the value of the specified key as the key of the set. If multiple data items have the same key, only the last one will appear in the new set:

 $collection = collect([ ['product_id' => 'prod-100', 'name' => 'desk'], ['product_id' => 'prod-200', 'name' => 'chair'], ]); $keyed = $collection->keyBy('product_id'); $keyed->all(); /* [ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ] */

You can also pass your own callback to this method, which will return the processed key value as the new collection key:

 $keyed = $collection->keyBy(function ($item) { return strtoupper($item['product_id']); }); $keyed->all(); /* [ 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ] */

keys()

keys Method returns the keys of all collections:

 $collection = collect([ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $keys = $collection->keys(); $keys->all(); // ['prod-100', 'prod-200']

last()

last Method returns the last element of the set that passed the truth test:

 collect([1, 2, 3, 4])->last(function ($value, $key) { return $value

You can also call parameterless last Method to get the last element of the collection. If the collection is empty. return null

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

macro()

static state macro() Methods allow you to add methods to Collection Class, see more details Extended Collection Some documents.

make()

The static make method will create a new collection instance. See details Create Collection Some documents.

map()

map Method traverses the set and passes each value to the given callback. This callback can modify the data item and return, thus generating a new modified collection:

 $collection = collect([1, 2, 3, 4, 5]); $multiplied = $collection->map(function ($item, $key) { return $item * 2; }); $multiplied->all(); // [2, 4, 6, 8, 10]
Note: Like most set methods, map Return a new collection instance; It does not modify the instance being called. If you want to change the original collection, use transform method.
mapInto()

mapInto() The method will iterate the collection and create a new instance for the given class by passing the value to the constructor:

 class Currency { /** * Create a new currency instance. * * @param  string  $code * @return void */ function __construct(string $code) { $this->code = $code; } } $collection = collect(['USD', 'EUR', 'GBP']); $currencies = $collection->mapInto(Currency::class); $currencies->all(); // [Currency('USD'), Currency('EUR'), Currency('GBP')]

mapSpread()

mapSpread Method will iterate over collection items, passing each nested collection item value to the given callback. In the callback, we can modify the collection items and return them, so that the modified values can be combined into a new collection:

 $collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); $chunks = $collection->chunk(2); $sequence = $chunks->mapSpread(function ($odd, $even) { return $odd + $even; }); $sequence->all(); // [1, 5, 9, 13, 17]

mapToGroups()

mapToGroups The method will group the collection items through the given callback, and the callback will return an associative array containing a single key value pair, thus combining the grouped values into a new collection:

 $collection = collect([ [ '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' => ['Johhny Doe'], ] */ $grouped->get('Sales')->all(); // ['John Doe', 'Jane Doe']

mapWithKeys()

mapWithKeys Method iterates over the collection and passes each value to the given callback, which returns an associated array containing key value pairs:

 $collection = collect([ [ 'name' => 'John', 'department' => 'Sales', 'email' => ' john@example.com ' ], [ 'name' => 'Jane', 'department' => 'Marketing', 'email' => ' jane@example.com ' ] ]); $keyed = $collection->mapWithKeys(function ($item) { return [$item['email'] => $item['name']]; }); $keyed->all(); /* [ ' john@example.com ' => 'John', ' jane@example.com ' => 'Jane', ] */

max()

max Method returns the maximum value of the given key in the collection:

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

median()

median Method will return the median

 $median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo'); // 15 $median = collect([1, 1, 2, 4])->median(); // 1.5

merge()

merge Method to merge the given array into a collection. Any string key in the array that matches the string key in the collection will overwrite the value in the collection:

 $collection = collect(['product_id' => 1, 'name' => 'Desk']); $merged = $collection->merge(['price' => 100, 'discount' => false]); $merged->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]

If the key of a given array is a number, the value of the array will be appended to the collection:

 $collection = collect(['Desk', 'Chair']); $merged = $collection->merge(['Bookcase', 'Door']); $merged->all(); // ['Desk', 'Chair', 'Bookcase', 'Door']

min()

min Method returns the minimum value of the given key in the collection:

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

mode()

mode Method will return the Mode

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

nth()

nth The n-th element in the method combination set creates a new set:

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

You can also pass an offset (offset position) as the second parameter:

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

only()

only Method returns the collection item of the specified key in the collection:

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

And only The relative method is except method.

pad()

pad Method fills the array with the given value until the specified maximum length is reached. This method and PHP function array_pad similar.

If you want to fill the data to the left, you need to specify a negative length. If the absolute value of the specified length is less than or equal to the array length, no filling will be done:

 $collection = collect(['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()

partition Method can be compared with PHP function list To be used together to separate those that pass the truth test from those that fail:

 $collection = collect([1, 2, 3, 4, 5, 6]); list($underThree, $aboveThree) = $collection->partition(function ($i) { return $i

pipe()

pipe Method passes the collection to the given callback and returns the result:

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

pluck()

pluck Method gets all set values for the given key:

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

You can also specify how you want the result set to set keys:

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

pop()

pop Method to remove and return the last data item in the collection:

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

prepend()

prepend Method to add a data item to the beginning of the collection:

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

You can also pass the second parameter to the key used to set the predecessor:

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

pull()

pull Method removes the data item from the collection by key and returns it:

 $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']); $collection->pull('name'); // 'Desk' $collection->all(); // ['product_id' => 'prod-100']

push()

push Method appends data items to the end of the set:

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

put()

put Method to set the given key and value in the collection:

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

random()

random Method returns random data items from a collection:

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

You can pass an integer data to random Function to specify the number of returned data. If the integer value is greater than 1, a set will be returned:

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

reduce()

reduce The method is used to reduce the collection to a single value and pass the results of each iteration to the sub iteration:

 $collection = collect([1, 2, 3]); $total = $collection->reduce(function ($carry, $item) { return $carry + $item; }); // 6

At the first iteration $carry The value of is null However, you can pass the second parameter to reduce To specify its initial value:

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

reject()

reject Method filters the collection using the given callback, which should return all data items it wants to remove from the result collection true

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

and reject The relative method is filter method.

reverse()

reverse Method reverses the order of set data items:

 $collection = collect(['a', 'b', 'c', 'd', 'e']); $reversed = $collection->reverse(); $reversed->all(); /* [ 4 => 'e', 3 => 'd', 2 => 'c', 1 => 'b', 0 => 'a', ] */

search()

search The method queries the set for the given value, returns the corresponding key if it is found, or returns the key if it is not found false

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

The above search uses "loose" comparison, and "strict" comparison true As the second parameter to this method:

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

In addition, you can also pass your own callback to search the first data item that passes the truth test:

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

shift()

shift Method to remove from the collection and return the first data item:

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

shuffle()

shuffle Method: Randomly scramble the data items in the set:

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

slice()

slice Method returns a slice of the collection from the given index:

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

If you want to limit the size of the returned slice, pass the size value to the method as the second parameter:

 $slice = $collection->slice(4, 2); $slice->all(); // [5, 6]

The returned slice has a new, digitally indexed key. If you want to keep the original key, you can use values Method to re index them.

sort()

sort Method to sort the collection. The sorted collection keeps the original array key. In this example, we use values Method reset key to consecutive numbered index:

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

If you need more advanced sorting, you can use your own algorithm to send a callback to sort method. Refer to the official PHP documentation about uasort Description of, sort The method is called at the bottom of the method.

Note: To sort nested sets and objects, view sortBy and sortByDesc method.
sortBy()

sortBy Method The set is sorted by the given key. The sorted set keeps the original array index. In this example, use values Method reset key to continuous index:

 $collection = collect([ ['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], ] */

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

 $collection = collect([ ['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 and sortBy The usage is the same, but the difference is that they are sorted in reverse order.

splice()

splice Method removes from the given location and returns the data item slice:

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

You can pass parameters to limit the size of the returned chunk:

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

In addition, you can pass the third parameter containing the new data item to replace the data item removed from the collection:

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

split()

split Method Group sets by given values:

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

sum()

sum Method returns the sum of all data items in the collection:

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

If the collection contains nested arrays or objects, a key should be passed to determine which values to sum:

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

In addition, you can also pass your own callback to determine which values to sum:

 $collection = collect([ ['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()

take Method returns a new collection using the specified number of data items:

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

You can also get a specified number of data items from the end of the set by passing negative numbers:

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

tap()

tap Method will pass the collection to the given callback, allowing you to enter the collection at the specified entry and process the collection items without affecting the collection itself:

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

times()

By static times() Method can create a new collection by calling the callback for a specified number of times:

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

This method is created together with the factory method Eloquent Model is very useful:

 $categories = Collection::times(3, function ($number) { return factory(Category::class)->create(['name' => 'Category #'.$number]); }); $categories->all(); /* [ ['id' => 1, 'name' => 'Category #1'], ['id' => 2, 'name' => 'Category #2'], ['id' => 3, 'name' => 'Category #3'], ] */

toArray()

toArray Method to convert the collection into a native PHP array. If the value of the collection is an Eloquent model, the model will also be converted into an array:

 $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* [ ['name' => 'Desk', 'price' => 200], ] */
Note: toArray All nested objects are also converted to arrays. If you want to get the underlying array, use all method.
toJson()

toJson Method to convert the collection into JSON:

 $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toJson(); // '{"name":"Desk","price":200}'

transform()

transform Method iterates over the collection and calls the given callback for each data item in the collection. The data items in the collection will be replaced with the values returned from the callback:

 $collection = collect([1, 2, 3, 4, 5]); $collection->transform(function ($item, $key) { return $item * 2; }); $collection->all(); // [2, 4, 6, 8, 10]
Note: Unlike most other set methods, transform Modify the collection itself. If you want to create a new collection, use map method.
union()

union Method to add a given array to the collection. If the given array contains a value that already exists in the original collection, the value of the original collection will be retained:

 $collection = collect([1 => ['a'], 2 => ['b']]); $union = $collection->union([3 => ['c'], 1 => ['b']]); $union->all(); // [1 => ['a'], 2 => ['b'], [3 => ['c']]

unique()

unique Method returns all unique data items in the collection. The returned collection retains the original array key. In this example, we use values Method to reset these keys to consecutive numeric indexes:

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

When processing nested arrays or objects, you can specify the key used to determine uniqueness:

 $collection = collect([ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], ]); $unique = $collection->unique('brand'); $unique->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ] */

You can also specify your own callback to judge the uniqueness of data items:

 $unique = $collection->unique(function ($item) { return $item['brand'].$ item['type']; }); $unique->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], ] */

unique The method uses "loose" comparison when checking data item values, that is, an integer string and an integer value are considered equal. If you want to use "strict" comparison, you can use uniqueStrict method.

uniqueStrict()

This method and unique Method signatures are the same, but all values are strictly compared.

unless()

unless Method will execute the given callback unless the first parameter passed to the method is equal to true

 $collection = collect([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]

And unless The relative method is when

unwrap()

static state unwrap The method returns the collection item from the given value:

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

values()

values Method returns a new set by resetting the set key to a continuous integer number:

 $collection = collect([ 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()

when The execution result of the method in the first parameter passed in is true Execute the given callback when:

 $collection = collect([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]

And when The relative method is unless

where()

where Method filters the collection by giving a key value pair:

 $collection = collect([ ['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], ] */

When checking data item values where Method uses "loose" comparison, that is, integer strings and integer arrays are equivalent. use whereStrict Methods Use "strict" comparison to filter.

whereStrict()

This method and where The usage signature is the same, but the difference is that all values use "strict" comparison.

whereIn()

whereIn Method filters the collection by the key values contained in the given array:

 $collection = collect([ ['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' => 'Bookcase', 'price' => 150], ['product' => 'Desk', 'price' => 200], ] */

whereIn Method Use "loose" comparison when checking data item values. To use "strict" comparison, you can use whereInStrict method.

whereInStrict()

This method and whereIn The method signatures are the same, but the difference is that whereInStrict Use "strict" comparisons when comparing values.

whereNotIn()

whereNotIn Method filters collection data items that are not in the given array by the given key value:

 $collection = collect([ ['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], ] */

whereNotIn Method uses a "loose" comparison when checking the value of a collection item, that is, integer strings and integer values are considered equal. For strict filtering, you can use whereNotInStrict method.

whereNotInStrict()

This method and whereNotIn Method signatures are the same, except that all values are compared strictly.

wrap()

static state wrap Method encapsulates the given value into the collection:

 $collection = Collection::wrap('John Doe'); $collection->all(); // ['John Doe'] $collection = Collection::wrap(['John Doe']); $collection->all(); // ['John Doe'] $collection = Collection::wrap(collect('John Doe')); $collection->all(); // ['John Doe']

zip()

zip Method merges the values of the given array at the index corresponding to the values of the collection:

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

High order messaging

Collections also support "higher-order messaging", that is, perform common functions on collections. The methods to support higher-order messaging include: average avg contains each every filter first map partition reject sortBy sortByDesc sum and unique

Each higher-order messaging can be accessed in the form of dynamic properties on the collection instance. For example, we use each Advanced messaging calls a method on each object of the collection:

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

Similarly, we can use sum Total number of votes aggregated by higher-order messaging:

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

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Key value pair Use of storage system Redis in Laravel

>>Next: Auxiliary function: a sharp tool to simplify Laravel code writing