gather


Introduction

  • Creating a collection
    • Extending a collection
    • Available methods
  • High-level information

Introduction

Illuminate\Support\Collection class provides a more readable and easier to handle array data encapsulation. Please see the code below for specific examples. We use the collect auxiliary function to create a new collection instance from the array, execute the strtoupper function on each element and then delete all empty elements:

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

As you can see, the Collection class allows you to chain calls to other methods to achieve smooth map and reduce operations on the underlying array. Generally, collections are immutable, which means that each Collection methods will all return a new Collection instance.

Create a collection

As mentioned above, the collect helper function will create a collection for the specified array Returns a new Illuminate\Support\Collection instance. Therefore, we can easily create a collection like this:

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

{tip} Usually, the results returned by Eloquent queries are Collection instances.

Extended collections

Collections are "macroable" (macroable), which allows You add other methods to the Collection class at execution time. For example, add a toUpper method to the Collection class with the following code:

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']

Normally, you should declare the collection macro inside a service provider.

Available methods

In the following document content, we will discuss each method of the Collection class. Keep in mind that all methods can operate on arrays in an elegant manner via chained access. Furthermore, almost all methods return a new Collection instance, allowing you to save an original copy of the collection if necessary: ​​

Method List

all()

all Method returns the underlying array represented by this collection:

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

##average()

avg Alias ​​for the method.

avg()

avg method returns the given Average of keys:

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

##chunk()

## The #chunk

method splits the collection into multiple small collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
This method is particularly suitable for views that use a grid system, such as Bootstrap

. Imagine you have a collection of Eloquent models that you want to display in a grid:

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

##collapse()

collapse Method merges a collection of multiple arrays into a collection of arrays:

$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 use the value of a set as a key, and then combine the value of another array or set as a value to form a set :

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

concat()

concat method will Append the given array or collection value 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 determines whether the collection contains the specified collection item:

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

contains

method to pass a set of keys/ Value pair, you can determine whether the 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 use the

contains

method to pass a callback function to perform your own real test: ## The #

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

method uses a "relaxed" comparison when checking the value of a collection item, which means that a string with an integer value will be treated as an integer equal to the same value. In contrast, the

containsStrict method uses "strict" comparison to filter.

##containsStrict()

This method is the same as contains

The method is similar, but it uses "strict" comparison to compare all values.

##count()

count method returns this collection The total number of items in the collection:
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4

##crossJoin()

The crossJoin

method cross-joins the values ​​of the specified array or collection, returning the Cartesian product of all possible permutations:
$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 is used to print collection items and interrupt script execution:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/
If you don’t want to interrupt script execution, use

dump method instead.

diff()

diff

method combines a collection with Other collections or pure PHP Arrays perform value comparisons. Then return the values ​​that exist in the original collection but do not exist in the specified collection:

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

##diffAssoc()

diffAssoc
method compares to another collection or PHP

array based on its keys and values. This method will return key/value pairs whose original collection does not exist in the specified 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 compares the keys of another collection or PHP array, and then returns the keys that exist in the original collection The key/value pair corresponding to the key does not exist in the specified 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]

##dump()

dump Method used to print collection items:

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

If you want to terminate the execution of the script after printing the collection, use

dd method instead.

##each()

each

method is used for looping Collection items and pass them into the callback function:

$collection->each(function ($item, $key) {
    //
});
If you want to break the loop over the collection items, then return

false

in your callback function:

$collection->each(function ($item, $key) {
    if (/* 某些条件 */ ) 
  { 
         return false;   
    
    }
 });

##eachSpread()

eachSpread

method is used to loop collection items. The value of each nested collection item is passed to the callback function:

$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
$collection->eachSpread(function ($name, $age) {
    //
 });
You can break the loop by returning false

in the callback function:

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

every()

every

method can be used to verify whether each element in the collection passes the specified Conditional test:

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

will return true:

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

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

corresponds to the

only method.

filter()

filter

method uses the given The callback function filters the collection and only retains those collection items that pass the specified condition test:

$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
  });
$filtered->all();
// [3, 4]
If no callback function is provided, all elements in the collection that return false

will be removed:

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

correspond to the

reject method.

first()

first

method returns the collection Test the first element by specifying the condition:

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

method without passing in parameters to get the first element in the collection. If the collection is empty,

null will be returned:

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

firstWhere()

firstWhere The method returns the first element in the collection containing the specified key/value pair:

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

You also The firstWhere method can be called using operators:

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

Like the where method, you can pass an argument to the firstWhere method. In this case, the firstWhere method will return the first collection item whose value is "true" for the specified key:

$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]

flatMap()

flatMap method iterates through the collection and passes each value in it to the given callback function. You can modify collection items and return them through callback functions, thus forming a new modified collection. Then, the arrays converted from the set are of the same level:

$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 Method converts a multi-dimensional collection into a one-dimensional collection:

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

You can optionally pass in the "depth" parameter:

$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 example, call

flatten If the depth parameter is not passed in, the nested array will be converted into one-dimensional, and then ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung'] will be returned. . Passing in the depth parameter allows you to limit the number of levels in the returned array.

flip()

flip method will Exchange keys and corresponding values:

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

##forget()

# The ##forget

method will remove the corresponding content from the collection by the specified key:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$collection->forget('name');$collection->all();
// ['framework' => 'laravel']
{note} Unlike most collection methods,

forget
Will not return a new modified collection; it will modify the original collection directly.

##forPage()

forPage method Returns a new collection containing the specified page number of collection items. This method accepts the page number as its first argument and the number of items displayed per page as its second argument:

$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 collection item with the specified key. If the key does not exist in the collection, it returns

null

:

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor
You can pass a default value of your choice as the second argument:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value
You can even pass a callback function as the default value. If the specified key does not exist, the result of the callback function will be returned:

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

groupBy()

groupBy method groups collection items based on the specified 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'],
        ],
    ]
*/

You can pass a callback function to Replaces the key of a string. This callback function should return the value of the key you wish to use for grouping:

$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'],
        ],
    ]
*/

An array can be passed for multiple grouping criteria. Each array element will correspond to the corresponding level within 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 specified key exists in the collection:

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

##implode()

implode

method is used to merge collection items. Its parameters depend on the type of collection items. If the collection contains arrays or objects, you should pass the keys of the properties you wish to combine, and the strings you wish to put between the values ​​to "splice" them:

$collection = collect([
    ['account_id' => 1,'product' => 'Desk'],    
    ['account_id' => 2, 'product' => 'Chair'],
  ]);
$collection->implode('product', ', ');
// Desk, Chair
If the collection contains simple strings Or a numerical value, you only need to pass in the string used for "splicing" as the only parameter of this method:

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

## The #intersect()

intersect

method removes from the original collection any values ​​that do not exist in the specified

array or collection. The generated collection will retain the keys of the original collection:

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

##intersectByKeys()

intersectByKeys Method removes from the original collection any keys that do not exist in the specified

array

or 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, the isEmpty method returns

true

, otherwise, returns false

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

##isNotEmpty()

If the collection is not Empty, the

isNotEmpty method returns true

, otherwise, returns

false:

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

keyBy()

keyBy method uses the specified key as the key of the collection. If multiple collection items have the same key, only the last collection item will be displayed in the new collection:
$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 a callback function in this method. The value returned by this callback function will be used as the key of the collection:

$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 all keys in the collection:
$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 The method returns the last element in the collection that passes the specified condition test:

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

You can also not pass it Call the last method with the input parameters to get the last element in the collection. If the collection is empty, returns null:

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

##macro()

static

macro methods allow you to add methods to the Collection class at runtime. For more information, see the documentation for Extended Collections.

##make()

static

make

method can create A new collection instance. See the Creating a Collection section.

map()

map

method traverses the collection and merges Pass each value into the given callback function. This callback function can arbitrarily modify the collection items and return, thereby generating a new collection of modified collection items:

$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 other collection methods,
map

A new collection instance is returned; it does not modify the original collection. If you want to modify the original collection, please use the transform method.

##mapInto()

mapInto()

Method to iterate over a collection, creating new instances of a given class by passing values ​​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')]

The mapSpread()

mapSpread

method can traverse the collection items and assign the value of each nested item to the specified callback function. The callback function can freely modify the collection item and return, thereby generating a new collection of modified collection items:

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

mapToGroups()

mapToGroups

method groups collection items using the given callback function. The callback function should return an associative array containing a single key/value pair, resulting in a new collection of grouped values:

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

mapWithKeys()

mapWithKeys

method iterates through the collection and passes each value into the given callback function. This callback function will return an associative array containing a single key/value pair:

$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 The method returns the maximum value for the specified key:

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

median()

median method returns the median value of the specified key:

$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 will merge the specified array or collection into the original collection. If the string key of the given collection item matches the string key in the original collection, the value of the specified collection item will overwrite the value of the original collection:

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

If the key of the specified collection item is a number , these values ​​will be appended to the end of 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 specified key:

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

##mode()

mode

The method returns the mode of the specified key:

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

nth()

nth

method creates a new collection consisting of every nth element:

$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']
You can choose to pass in An offset position as the second argument:

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

##only()

The only

method returns all collection items with 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

correspond to the

except method.

##pad()

pad method will be used to Fills the array with specified values ​​until the array reaches the specified size. This method behaves similarly to the

array_pad

PHP function. To fill to the left, you should use negative values. If the absolute value of the given size is less than or equal to the length of the array, no padding will occur:

$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 used in conjunction with the

list

in the PHP function to separate elements that pass the specified condition and those that do not. :

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

pipe()

pipe method will The collection is passed to the specified callback function and the result is returned:

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

##pluck()

pluck The method can obtain all values ​​corresponding to the specified key in the collection:
$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 the key to generate the collection by passing in the second parameter:

$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
If there are duplicate keys, the last matching element will be inserted into the popped collection:
$collection = collect([
    ['brand' => 'Tesla',  'color' => 'red'],    
    ['brand' => 'Pagani', 'color' => 'white'],    
    ['brand' => 'Tesla',  'color' => 'black'],    
    ['brand' => 'Pagani', 'color' => 'orange'],
  ]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']

pop()

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

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

prepend()

prepend method adds the specified value 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 set the key of the newly added collection item:

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

pull( )

pull method removes the value corresponding to the specified key from the collection and returns:

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

push()

push method appends the specified value to the end of the collection item:

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

put()

put method sets the given key-value pair within 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 from collection Returns a random item in:

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

You can choose to pass an integer to

random to specify the number of random items to be obtained. As long as you explicitly pass the quantity you wish to receive, a collection of items will be returned:

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

If the collection has less than the specified number of items, this method will throw

InvalidArgumentException.

reduce()

reduce method will The result of the iteration is passed to the next iteration until the set is reduced to a single value:

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

The value of

$carry on the first iteration is null; however, you also Its initial value can be specified by passing the second argument to reduce:

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

## The #reject()

reject

method filters the collection using the specified callback function. If the callback function returns true, the corresponding collection item will be removed from the collection:

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

reject

methods correspond to filter method.

reverse()

reverse

method is used to reverse Order of collection items, retaining original keys:

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

search()

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

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

Uses a "relaxed" approach to searching, which means that strings with integer values ​​are considered equal to integers of the same value. To search in a "strict" way, pass true as the second parameter of the method:

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

Alternatively, you can pass a callback function to search for the first string that passes the conditional test. A collection item:

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

shift()

shift Method removes and returns the first collection item of the collection:

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

##shuffle()

shuffle Method randomly shuffles collection items:

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

##slice()

slice

The method returns the part of the collection starting at 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 content, you can set the size you expect Passed to this method as the second argument:

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

By default, the returned content will retain the original keys. If you do not wish to retain the original keys, you can use the

values method to re-index.

##some()

contains

Alias ​​of method.

sort()

sort

method sorts the collection Sort. The sorted collection will retain the keys of the original array, so in this example we will use the

values method to reset the keys to consecutively numbered indices:

$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
If you have more advanced sorting needs, you can pass the callback function to sort

with your own algorithm. See the PHP documentation for

uasort which is what the collection's sort method calls under the hood. {tip} If you need to sort nested arrays or objects, please refer to

sortBy

and sortByDesc method.

sortBy()

sortBy method will sort the collection based on the specified key. The sorted collection retains the keys of the original array, so in this example we use the values method to reset the keys to consecutively numbered indices:

$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 You can also pass your own callback function to determine how to sort the collection's values:

$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 is the same as the sortBy method, but sorts the collection in reverse order.

sortKeys()

sortKeys method passes the underlying association Array keys to sort the collection:

$collection = collect([ 
   'id' => 22345,    
   'first' => 'John',    
   'last' => 'Doe',
  ]);
$sorted = $collection->sortKeys();$sorted->all();
/*
    [
        'first' => 'John',
        'id' => 22345,
        'last' => 'Doe',
    ]
*/

##sortKeysDesc()

The The method is the same as the

sortKeys method, but sorts the collection in reverse order.

splice()

splice method removes and Returns the collection item fragment starting at the specified index:

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

You can pass a second parameter to limit the size of the deleted content:

$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 in a new parameter item The third parameter is used to replace the deleted collection items in 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 splits the collection according to the given value:

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

##sum ()

sum

The method returns the sum of all 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 in Specify the values ​​to be summed:
$collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],    
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
  ]);
$collection->sum('pages');
// 1272

Alternatively, you can pass in your own callback function to decide which values ​​in the collection are to be summed:

$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 with the given number of items:

$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
You can also pass a negative integer to get a specified number of items from the end of the collection:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]

##tap()

tap method passes the given callback function into the collection, allowing you to "tap" the collection at a specific point and perform operations on the collection items without affecting the collection itself. Certain operations:

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

times()

statictimes method creates a new collection by calling the callback function a given number of times:

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

Use this method Can be used in conjunction with factories to create Eloquent models:

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

##toArray()

The

toArray method converts a collection into a PHP array. If the collection's value is an Eloquent model, that will also be converted to an array:

$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/

{note}

toArray will also convert all collection's nested objects to arrays. If you want to get the original array, you can use the all method.

##toJson()

toJson

method Convert the collection into a JSON string:

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

##transform()

## The #transform method iterates over the collection and calls the given callback function for each collection item. The contents of the collection will also be replaced by the return value of the callback function:

$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 collection methods, transform

will modify the collection itself. If you want to create a new collection, you can use the

map method.

##union()

union Method Adds the given array to the collection. If the given array contains the same keys as the original collection, the values ​​of the original collection will not be changed:
$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]

## The #unique()

unique

method returns all unique items in the collection. The returned collection retains the keys of the original array, so in this example we use the values

method to reset the keys to consecutively numbered indices:

$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
in When working with 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 determine the uniqueness of an item by passing your own callback function:
$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'],
    ]
*/
# The ##unique

method uses "relaxed" mode comparison when checking item values, meaning that strings with integer values ​​will be treated as integers equal to the same value. You can do "strict" mode comparison using the

uniqueStrict

method.

#uniqueStrict()

This method is the same as

unique

The method is the same, however, all values ​​are compared using "strict" mode.

unless()

unless When the first parameter passed in is not true, the given method will be executed The callback function:

$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 correspond to the when method.

#unlessEmpty()

whenNotEmpty Alias ​​of method.

#unlessNotEmpty()

whenEmpty Alias ​​of method.

##unwrap()

staticunwrap

method returns a collection Available values ​​inside:

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 collection with the keys reset to consecutive numbers:

$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

method When the first parameter passed in is

true, the given callback function will be executed:

$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

corresponds to the

unless method.

whenEmpty()

whenEmpty

method when the collection is When empty, the given callback function will be executed:

$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
  });
$collection->all();
// ['michael', 'tom']
$collection = collect();$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
  });
$collection->all();
 // ['adam']
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function($collection) {
    return $collection->push('adam');}, function($collection) {
        return $collection->push('taylor');
      });
$collection->all();
   // ['michael', 'tom', 'taylor']
and whenEmpty

correspond to the

whenNotEmpty method.

##whenNotEmpty()

whenNotEmpty Method when the collection is not When it is empty, the given callback function will be executed:

 $collection = collect(['michael', 'tom']);
 $collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
   });
 $collection->all();
    // ['michael', 'tom', 'adam']
 $collection = collect();
 $collection->whenNotEmpty(function ($collection) {
     return $collection->push('adam');
   });
  $collection->all();
  // []
  $collection = collect();
  $collection->whenNotEmpty(function($collection) {
      return $collection->push('adam');
    }, 
  function($collection) {
        return $collection->push('taylor');
       });
   $collection->all();
 // ['taylor']

and whenNotEmpty correspond to the

whenEmpty method.

##where()

where method passes the given The key/value pair filter collection:
$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],
    ]
*/

where method uses "relaxed" mode comparison when checking collection item values, which means that strings with integer values ​​are considered equal to the same Integer value. You can perform "strict" mode comparisons using the

whereStrict

method.

#whereStrict()

This method is the same as

where The method is similar; the difference is that the "strict" mode comparison will be used.

whereBetween()

whereBetween The method will filter the collection using the given range:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],    
    ['product' => 'Chair', 'price' => 80],    
    ['product' => 'Bookcase', 'price' => 150],    
    ['product' => 'Pencil', 'price' => 30],    
    ['product' => 'Door', 'price' => 100],
 ]);
$filtered = $collection->whereBetween('price', [100, 200]);
$filtered->all();
/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
    ]
*/

whereIn()

whereIn will filter the collection based on the key/value pairs that contain 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 uses a "relaxed" comparison to check the value of a collection item, which means that a string with an integer value is treated as an integer equal to the same value. You can perform "strict" mode comparisons using the whereInStrict method.

#whereInStrict()

This method is the same as

whereIn The method is similar; the difference is that the "strict" mode is used for comparison.

##whereInstanceOf()

whereInstanceOf

method based on the specified Class to filter the collection:

$collection = collect([
    new User,    
    new User,    
    new Post,
 ]);
return $collection->whereInstanceOf(User::class);

whereNotBetween()

whereNotBetween

Method to filter the collection within the specified range:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],    
    ['product' => 'Chair', 'price' => 80],    
    ['product' => 'Bookcase', 'price' => 150],    
    ['product' => 'Pencil', 'price' => 30],    
    ['product' => 'Door', 'price' => 100],
  ]);
$filtered = $collection->whereNotBetween('price', [100, 200]);
$filtered->all();
/*
    [
        ['product' => 'Chair', 'price' => 80],
        ['product' => 'Pencil', 'price' => 30],
    ]
*/

##whereNotIn()

whereNotIn

The method filters the collection based on the specified key and the value that does not contain the specified array:

$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

The method uses "relaxed" mode comparison to check The value of a collection item, meaning that a string with an integer value will be treated as an integer equal to the same value. You can do "strict" mode comparisons using the

whereNotInStrict method.

##whereNotInStrict()

This method is the same as whereNotIn

The method is similar; the difference is that the "strict" mode is used for comparison.

wrap()

staticwrap method where appropriate Put the specified value in the collection if:

$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 specified array with the values ​​of the original collection at the corresponding index:
$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]

High-level messaging

Collections also provide support for "high-level messaging", which is a collection of shortcuts for common operations. Collection methods that support higher-order messaging 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 passing can be accessed as a dynamic property of the collection instance. For example, using each higher-order messaging to call a method on each object in the collection:

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

Similarly, we can use sum higher-order messaging to Collect the total number of "votes" in the users collection:

$users = User::where('group', 'Development')->get();
return $users->sum->votes;
This article was first published on the LearnKu.com website.