15 Awesome Laravel Collection Methods

Admin   Laravel   137  2020-08-12 21:00:37

Laravel Eloquent method uses Collections to return results. Collections contain very useful methods that make them very powerful and useful to use. You can filter them, modify them, and more with them very conveniently. Here I will give useful methods in this tutorial.

You now have a Post model. You find all the posts with PHP

$posts = App\Post::where('category', 'php')->get();

The above variable will return a Collection.

You can create a simple Collection by using the collection

$collection = collect([
    [
    'user_id' => '1',
    'title' => 'Helpers in Laravel',
    'content' => 'Create custom helpers in Laravel',
    'category' => 'php'
    ],
    [
    'user_id' => '2',
    'title' => 'Testing in Laravel',
    'content' => 'Testing File Uploads in Laravel',
    'category' => 'php'
    ],
    [
    'user_id' => '3',
    'title' => 'Telegram Bot',
    'content' => 'Crypto Telegram Bot in Laravel',
    'category' => 'php'
    ],
]);

Above is how you create a collection. You can apply all the Collection that Laravel provides.

Below I will introduce you to the commonly used functions

filter()

One of the useful methods, help you filter Collection with a callBack. It only passes for the correct items, while the others removed. Filter returns a new instance without changing the original instance.

$filter = $collection->filter(function($value, $key) {
    if ($value['user_id'] == 2) {
        return true;
    }
});
 
$filter->all();

all method returns the array below

[
    1 => [
        "user_id" => 2,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ]
]

search()

Used to search a collection for a certain value, if a value exists in a collection, then the value is returned. If the value does not match, then returns false.

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);
 
$names->search('Jason');
// 2

By default, a search is performed using loose comparisons. You can pass true as the second argument to methods search to use strict

You can also pass the callback function to the method search. It will return the key of the first item pass the callback

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);
 
$names->search(function($value, $key) {
    return strlen($value) == 6;
});
// 3

chunk()

The method used to split a collection into smaller collections. It is very useful when displaying collections into the gird

$prices = collect([18, 23, 65, 36, 97, 43, 81]);
 
$prices = $prices->chunk(3);
 
$prices->toArray();

Response from the above code

[
    0 => [
        0 => 18,
        1 => 23,
        2 => 65
    ],
    1 => [
        3 => 36,
        4 => 97,
        5 => 43
    ],
    2 => [
        6 => 81
    ]
]

dump()

Method dump collection items. It is very useful for debugging

$collection->whereIn('user_id', [1, 2])
    ->dump()
    ->where('user_id', 1);


Response from the above code

15 Awesome Laravel Collection Methods

map()

Used to iterate over the full collection. It accepts a callback as an argument.value and the key passed to the callback can change the values ​​and return them. Finally, return a new collection.

$changed = $collection->map(function ($value, $key) {
    $value['user_id'] += 1;
    return $value;
});
 
return $changed->all();

Response from the above code

[
    [
        "user_id" => 2,
        "title" => "Helpers in Laravel",
        "content" => "Create custom helpers in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 3,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 4,
        "title" => "Telegram Bot",
        "content" => "Crypto Telegram Bot in Laravel",
        "category" => "php"
    ]
];

whereNotIn()

You can use the whereNotIn method to simply filter collections of value that are not in an array.

$collection->whereNotIn('user_id', [1, 2]);

max()

Returns the maximum value for a given key. You can find the largest user_id.

$collection->max('user_id');

pluck()

Returns all values ​​for a key; it is very useful to extract the values ​​of a certain column.

$title = $collection->pluck('title');
$title->all();

Result

[
  "Helpers in Laravel",
  "Testing in Laravel",
  "Telegram Bot"
]

And pluck also accepts the second argument

$title = $collection->pluck('user_id', 'title');
$title->all();

The bottom result as you see

[
    "Helpers in Laravel" => 1,
    "Testing in Laravel" => 2,
    "Telegram Bot" => 3
]

each()

The each method is used to repeat the entire collection. It accepts a callback with two parameters.

$collection->each(function ($item, $key) {
    info($item['user_id']);
});

isEmpty()/isNotEmpty()

In addition to checking for 1 collections for which records are not equal to count(), you can use isEmpty() / isNotEmpty()

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

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

contains()

The contains method is used to check if a collection contains a unique value. It will return true when pass

$contains = collect(['country' => 'USA', 'state' => 'NY']);
 
$contains->contains('USA');
// true
 
$contains->contains('UK');
// false

If you use the key/value for the method, it checks to see if the given value exists

$collection->contains('user_id', '1');
// true
 
$collection->contains('title', 'Not Found Title');
// false

And you can also use callback for methods. The callback will run for all items in the collection and will return results if the condition passes.

$collection->contains(function ($value, $key) {
    return strlen($value['title']) < 13;
});
// true

forget()

It will remove items from the collection. You only need to pass the key and it will delete from the collection

$forget = collect(['country' => 'usa', 'state' => 'ny']);
 
$forget->forget('country')->all();


[
    "state" => "ny"
]

Note: forget doesn't work on a multidimensional array

avg()

This function returns the mean

$avg = collect([
    ['shoes' => 10],
    ['shoes' => 35],
    ['shoes' => 7],
    ['shoes' => 68],
])->avg('shoes');

// 30

groupBy()

Group collections by key

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

random()

Returns any result in the collection

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

You can use these laravel collection methods to work on your own projects.

The above are 15 commonly used methods. There are also many other common methods that handle collections. You can refer to here

Wish you success. ^^