Debug School

rakesh kumar
rakesh kumar

Posted on

Explain Collections Methods Part-II

  1. each
  2. eachSpread
  3. every
  4. except
  5. filter
  6. first
  7. firstOrFail
  8. firstWhere
  9. flatMap
  10. flatten
  11. flip
  12. forget
  13. forPage
  14. get
  15. groupBy
  16. has
  17. hasAny
  18. implode
  19. intersect
  20. intersectByKeys
  21. isEmpty
  22. isNotEmpty
  23. join
  24. keyBy
  25. keys
  26. last

each()
The each method iterates over the items in the collection and passes each item to a closure:

$collection->each(function ($item, $key) {
    //
});
Enter fullscreen mode Exit fullscreen mode

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

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

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

$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);

$collection->eachSpread(function ($name, $age) {
    //
});
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

// false
Enter fullscreen mode Exit fullscreen mode

If the collection is empty, the every method will return true:

$collection = collect([]);

$collection->every(function ($value, $key) {
    return $value > 2;
});

// true
Enter fullscreen mode Exit fullscreen mode

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

$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);

$filtered = $collection->except(['price', 'discount']);

$filtered->all();

// ['product_id' => 1]
Enter fullscreen mode Exit fullscreen mode

For the inverse of except, see the only method.

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

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

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

$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [3, 4]
Enter fullscreen mode Exit fullscreen mode

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

$collection = collect([1, 2, 3, null, false, '', 0, []]);

$collection->filter()->all();

// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

For the inverse of filter, see the reject method.

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

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

// 3
Enter fullscreen mode Exit fullscreen mode

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

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

// 1
Enter fullscreen mode Exit fullscreen mode

firstOrFail()
The firstOrFail method is identical to the first method; however, if no result is found, an Illuminate\Support\ItemNotFoundException exception will be thrown:

collect([1, 2, 3, 4])->firstOrFail(function ($value, $key) {
    return $value > 5;
});
Enter fullscreen mode Exit fullscreen mode

// Throws ItemNotFoundException...

You may also call the firstOrFail method with no arguments to get the first element in the collection. If the collection is empty, an Illuminate\Support\ItemNotFoundException exception will be thrown:

collect([])->firstOrFail();
Enter fullscreen mode Exit fullscreen mode

// Throws ItemNotFoundException...

firstWhere()
The firstWhere method returns the first element in the collection with the given 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]
Enter fullscreen mode Exit fullscreen mode

You may also call the firstWhere method with a comparison operator:

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

// ['name' => 'Diego', 'age' => 23]
Enter fullscreen mode Exit fullscreen mode

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

$collection->firstWhere('age');

// ['name' => 'Linda', 'age' => 14]
Enter fullscreen mode Exit fullscreen mode

flatMap()
The flatMap method iterates through the collection and passes each value to the given closure. The closure is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by one 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'];
Enter fullscreen mode Exit fullscreen mode

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

$collection = collect([
    'name' => 'taylor',
    'languages' => [
        'php', 'javascript'
    ]
]);

$flattened = $collection->flatten();

$flattened->all();

// ['taylor', 'php', 'javascript'];
Enter fullscreen mode Exit fullscreen mode

If necessary, you may pass the flatten method a "depth" argument:

$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'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

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

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

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

$flipped = $collection->flip();

$flipped->all();

// ['taylor' => 'name', 'laravel' => 'framework']
Enter fullscreen mode Exit fullscreen mode

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

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

$collection->forget('name');

$collection->all();

// ['framework' => 'laravel']
Enter fullscreen mode Exit fullscreen mode

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

forPage()
The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:

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

$chunk = $collection->forPage(2, 3);

$chunk->all();

// [4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

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

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

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

// taylor
Enter fullscreen mode Exit fullscreen mode

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

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

$value = $collection->get('age', 34);

// 34
Enter fullscreen mode Exit fullscreen mode

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

$collection->get('email', function () {
    return 'taylor@example.com';
});

// taylor@example.com
Enter fullscreen mode Exit fullscreen mode

groupBy()
The groupBy method groups the collection's items by a 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->all();

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

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

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

$grouped->all();

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

Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional 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']],
        ],
    ],
];
*/
Enter fullscreen mode Exit fullscreen mode

has()
The has method determines if a given 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
Enter fullscreen mode Exit fullscreen mode

hasAny()
The hasAny method determines whether any of the given keys exist in the collection:

$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);

$collection->hasAny(['product', 'price']);

// true

$collection->hasAny(['name', 'price']);

// false
Enter fullscreen mode Exit fullscreen mode

implode()
The implode method joins items in a collection. Its arguments depend on the type of items in the collection. If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the "glue" string you wish to place between the values:

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

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

// Desk, Chair

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

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

// '1-2-3-4-5'
Enter fullscreen mode Exit fullscreen mode

You may pass a closure to the implode method if you would like to format the values being imploded:

$collection->implode(function ($item, $key) {
    return strtoupper($item['product']);
}, ', ');

// DESK, CHAIR
Enter fullscreen mode Exit fullscreen mode

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

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

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

$intersect->all();

// [0 => 'Desk', 2 => 'Chair']
Enter fullscreen mode Exit fullscreen mode

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

intersectByKeys()
The intersectByKeys method removes any keys and their corresponding values from the original collection that are not present in the given 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]
Enter fullscreen mode Exit fullscreen mode

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

collect([])->isEmpty();

// true
Enter fullscreen mode Exit fullscreen mode

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

collect([])->isNotEmpty();

// false
Enter fullscreen mode Exit fullscreen mode

join()
The join method joins the collection's values with a string. Using this method's second argument, you may also specify how the final element should be appended to the string:

collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
collect(['a'])->join(', ', ' and '); // 'a'
collect([])->join(', ', ' and '); // ''
Enter fullscreen mode Exit fullscreen mode

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

$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'],
    ]
*/
Enter fullscreen mode Exit fullscreen mode

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

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

$keyed->all();

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

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

$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']
Enter fullscreen mode Exit fullscreen mode

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

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

// 2

Enter fullscreen mode Exit fullscreen mode

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

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

// 4
Enter fullscreen mode Exit fullscreen mode

Top comments (0)