In today’s Laravel Certification exam review series, I would like to introduce collections, the purpose of which is to note down the knowledge for myself and you to follow the article with a “detailed” document.
Start!
I. Collections Overview
Collection in Laravel is a powerful and flexible data structure that allows you to work with a collection of elements in various forms. Collection provides you with methods to filter, sort, transform, and manipulate the data in that collection.
Collection is designed to work efficiently with PHP databases and functions. It can be used to process data returned from database queries, or to filter, sort, and display complex collections.
Some of the Collection features in Laravel include:
- Methods to filter and sort the elements in the collection based on different conditions.
- Methods to transform data in a collection by adding or removing elements.
- Methods to perform operations like map, reduce, and filter on the collection.
- The ability to combine collections together to create new collections.
- Methods to handle collection elements in a flexible way.
- Ability to use collections with Eloquent to query and sort data in the database.
With Collection, you can perform complex operations on a collection of elements easily and efficiently, saving you time and increasing the performance of your Laravel application.
II. Collections functions in Laravel 9
In summary, there are nearly 70 collections functions in Laravel and I would like to explain each function in detail. This post can be quite long, but it contains a lot of information
I will apply this collect pattern, please remember to the end of the article.
12 collect(['Vietnam', 'Japan', 'Korea', 'Thailand']);
1. Add elements in collections
Add an element to the collection:
- push($value) : Add an element to the end of the collection (1 element or an array of elements).
1 2 3 4 | Ví dụ: `dd($countries->push("American"))` hoặc `dd($countries->push(["American"]))` => Kết quả lần lượt là : |
and
- put($key, $value) : Add or update an element or an array with the corresponding key in the collection. If
$key
already exists,put
will overwrite the newvalue
; otherwise, it will add the correspondingkey
andvalue
.Example:dd($countries->put(2, "American"))
1 2 | Ví dụ: `dd($countries->put(6, "American"))` |
- prepend($value) : Add an element to the beginning of the collection.Example:
dd($countries->prepend(2, "American"))
2. Delete an element in the collection
- forget($key) : Remove the element with the corresponding key from the collection, if the key is not there, nothing will happen.Example:
dd($countries->forget(1))
- pull($key, $default = null) : Removes the element with the corresponding key from the collection and returns the value of that element, if the key does not exist, returns null . Suppose we set the variable
$default = "ahihihi"
then displayahihihi
instead ofnull
- pop() : Removes the last element from the collection and returns its value.
- reject($callback) : Removes all elements in the collection that do not satisfy the callback function’s condition. (This is also a method to filter elements that do not satisfy the condition of the callback function in the collection, but if someone asks you to list some methods to delete, this method also satisfies the condition, obviously it deletes that)For example:
1 2 3 4 | $countries = $countries->reject(function($var) { return in_array($var, ['Vietnam', 'Japan']); }); |
3. Editing an element in a collection
- transform($key) : Apply a callback function to each element of the collection and overwrite the old values with the new values.
For example
1 2 3 4 5 6 7 8 9 10 | $test = $countries->transform(function($country) { if (in_array($country, ["Vietnam", "Japan"])) { return $country . "ese"; } else { return $country; } }); dd($test, $countries); |
- map($callback) : Creates a new collection by applying a callback function to each element of the collection.
1 2 3 4 5 6 7 8 9 10 | $test = $countries->map(function($country) { if (in_array($country, ["Vietnam", "Japan"])) { return $country . "ese"; } else { return $country; } }); dd($test, $countries); |
- merge($items) : Creates a new collection by combining the current collection with another collection or an array.
For example we have the following:
1 2 3 4 5 | //Tạo thêm 1 collect mới $countries2 = collect(['American', 'HongKong', 'China', 'Lao']); $test = $countries->merge($countries2); dd($test, $countries); |
- replace($items) : Creates a new collection by replacing all elements in the collection with other elements provided in a new array or collection.
1 2 3 4 5 | //Tạo thêm 1 collect mới $countries2 = collect(['American', 'HongKong', 'China', 'Lao']); $test = $countries->replace($countries2); dd($test, $countries); |
4. Sort the elements in the collection
- sort() : Sorts a Collection in ascending order of the element’s value.
1 2 3 4 | $collection = collect([3, 2, 1, 5, 4]); $sorted = $collection->sort(); // Kết quả: [1, 2, 3, 4, 5] |
- sortBy($key) : Sorts a Collection using a
key
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $collection = collect([ ['name' => 'John', 'age' => 22], ['name' => 'Bob', 'age' => 25], ['name' => 'Jane', 'age' => 20], ]); $sorted = $collection->sortBy('age'); // Kết quả: /* collect([ ['name' => 'Jane', 'age' => 20], ['name' => 'John', 'age' => 22], ['name' => 'Bob', 'age' => 25], ]); */ |
- sortByDesc($key) : Sorts a Collection in descending order using a
key
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $collection = collect([ ['name' => 'John', 'age' => 22], ['name' => 'Bob', 'age' => 25], ['name' => 'Jane', 'age' => 20], ]); $sorted = $collection->sortByDesc('age'); // Kết quả: /* collect([ ['name' => 'Bob', 'age' => 25], ['name' => 'John', 'age' => 22], ['name' => 'Jane', 'age' => 20], ]); */ |
- sortKeys() : Sorts a Collection in ascending order of the key of the elements.
1 2 3 4 5 6 7 8 9 | $collection = collect([ 'product_3' => ['name' => 'Product 3', 'price' => 300], 'product_1' => ['name' => 'Product 1', 'price' => 100], 'product_2' => ['name' => 'Product 2', 'price' => 200], ]); $sorted = $collection->sortKeys(); dd($sorted); |
Result:
1 2 3 4 5 6 | collect([ 'product_1' => ['name' => 'Product 1', 'price' => 100], 'product_2' => ['name' => 'Product 2', 'price' => 200], 'product_3' => ['name' => 'Product 3', 'price' => 300], ]); |
- sortKeysDesc() : Sorts a Collection in descending order of the key of the elements.
1 2 3 4 5 6 7 8 9 10 | $data = collect([ ['name' => 'Alice', 'age' => 25], ['name' => 'Bob', 'age' => 20], ['name' => 'Charlie', 'age' => 30] ]); $result = $data->sortKeysDesc(); dd($result->all()); |
Result:
1 2 3 4 5 6 | [ ['name' => 'Charlie', 'age' => 30], ['name' => 'Bob', 'age' => 20], ['name' => 'Alice', 'age' => 25] ] |
5. Filter elements in the collection
- filter($callback) : Filters the elements of the collection based on the condition specified in
$callback
and returns a new collection containing the filtered elements.
1 2 3 4 5 6 7 8 9 10 11 | $collection = collect([1, 2, 3, 4]); $filtered = $collection->filter(function ($value, $key) { return $value > 2; }); $filtered->all(); // Kết quả // [3, 4] |
- reject($callback) : Similar to the filter() method, but returns the elements that do not satisfy the condition.
1 2 3 4 5 6 7 8 9 10 11 | $collection = collect([1, 2, 3, 4]); $filtered = $collection->filter(function ($value, $key) { return $value > 2; }); $filtered->all(); // Kết quả // [1, 2] |
- where($key, $operator, $value = null) : Filters the elements of the collection based on the value of an attribute. $key is the property name, $operator is the comparison operator (eg =, >, <…), and $value is the value to compare. If there are only 2 parameters in function where => default operator is “=”
1 2 3 4 5 6 7 8 9 10 11 | $collection = collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100], ]); $filtered = $collection->where('price', '>', 100); dd($filtered->all()); |
Result:
1 2 3 4 5 | [ ['product' => 'Desk', 'price' => 200], ['product' => 'Bookcase', 'price' => 150] ] |
- whereStrict($key, $value) : Similar to the where() method, but compares the value of the attribute and $value by the exact comparison type (including data type). For example
1 2 3 4 5 6 7 8 9 10 | $products = collect([ ['id' => 1, 'name' => 'Product A'], ['id' => '1', 'name' => 'Product B'], ['id' => 2, 'name' => 'Product C'], ]); $filtered = $products->whereStrict('id', 1); dd($filtered->all()); |
Result:
1 2 3 4 | [ ['id' => 1, 'name' => 'Product A'] ] |
- whereIn($key, $values) : Filters elements with a value of the
$key
attribute in an array of $values.
1 2 3 4 5 6 7 8 9 10 11 | $collection = collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100], ]); $filtered = $collection->whereIn('price', [150, 200]); dd($filtered->all()); |
Result:
1 2 3 4 5 | [ ['product' => 'Desk', 'price' => 200], ['product' => 'Bookcase', 'price' => 150], ] |
- whereInStrict($key, $values) : Similar to whereIn but will set additional data types. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $collection = collect([ ['product' => 'Desk', 'price' => '200'], ['product' => 'Chair', 'price' => 100], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100], ]); $filtered = $collection->whereInStrict('price', [150, 200]); $filtered->all(); /* Kết quả [ ['product' => 'Bookcase', 'price' => 150], ] */ |
- whereNotIn($key, $values) : Similar to whereIn() method, but filters elements that are not in the $values array.
1 2 3 4 5 6 7 8 9 10 11 | $collection = collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100], ]); $filtered = $collection->whereNotIn('price', [150, 200]); dd($filtered->all()); |
Result:
1 2 3 4 5 | [ ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100], ] |
- whereNotInStrict($key, $values) : Similar to the whereNotIn() method, but filters elements that are not in the $values array.
1 2 3 4 5 6 7 8 9 10 11 | $collection = collect([ ['product' => 'Desk', 'price' => '200'], ['product' => 'Chair', 'price' => 100], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100], ]); $filtered = $collection->whereNotIn('price', [150, 200]); dd($filtered->all()); |
Result:
1 2 3 4 5 6 | [ ['product' => 'Desk', 'price' => '200'], ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100] ] |
- whereBetween($key, $values) : Filters elements where the value of the $key attribute ranges from $values[0] to $values[1].
For example :
1 2 3 4 5 6 7 8 9 10 11 12 | $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]); dd($filtered->all()); |
Result:
1 2 3 4 5 6 | [ ['product' => 'Desk', 'price' => 200], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100] ] |
- whereNull($key) : Filters elements where the value of
$key
attribute isnull
.
1 2 3 4 5 6 7 8 9 10 | $collection = collect([ ['name' => 'Desk'], ['name' => null], ['name' => 'Bookcase'], ]); $filtered = $collection->whereNull('name'); dd($filtered->all()); |
Result:
1 2 3 4 | [ ['name' => null], ] |
- whereNotNull($key) : Filters elements whose value of the
$key
attribute isnull
.
1 2 3 4 5 6 7 8 9 10 | $collection = collect([ ['name' => 'Desk'], ['name' => null], ['name' => 'Bookcase'], ]); $filtered = $collection->whereNull('name'); dd($filtered->all()); |
Result:
1 2 3 4 5 | [ ['name' => 'Desk'], ['name' => 'Bookcase'] ] |
5. Collections support handling strings, arrays
- join($glue, $finalGlue = null) : used to combine the elements of a collection into a single string, with the elements separated by a specified string.
In there :
$glue
: is the string that separates the elements.$finalGlue
: is the string separating the last element and the preceding element. If you don’t want a string separator on the last element, the value of$finalGlue
will be null.
For example:
1 2 3 4 5 6 | $collection = collect(['apple', 'banana', 'cherry']); $joined = $collection->join(', ', ' and '); // Kết quả: "apple, banana, and cherry" |
- crossJoin(…$collections) : is a Collection method in Laravel, it is used to calculate all combinations of values in the provided collections.
For example :
1 2 3 4 5 6 | $colors = collect(['red', 'green']); $sizes = collect(['S', 'M', 'L']); $materials = collect(['cotton', 'polyester']); $combinations = $colors->crossJoin($sizes, $materials); |
Result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Collection [ ["red", "S", "cotton"], ["red", "S", "polyester"], ["red", "M", "cotton"], ["red", "M", "polyester"], ["red", "L", "cotton"], ["red", "L", "polyester"], ["green", "S", "cotton"], ["green", "S", "polyester"], ["green", "M", "cotton"], ["green", "M", "polyester"], ["green", "L", "cotton"], ["green", "L", "polyester"], ] |
- mapInto(string $class) : Apply a function to each element in the collection and return a new collection. In this case, we can use the map method to process the strings in the collection.
1 2 3 4 5 6 7 8 9 10 | $collection = collect([1, 2, 3, 4, 5]); $multiplied = $collection->map(function ($item, $key) { return $item * 2; }); dd($multiplied->all()); //Kết quả: [2, 4, 6, 8, 10] |
- mapSpread($callback) : is a collection method in Laravel, used to transform elements in the Collection using a callback function, but with a different behavior than the
map()
andmapWithKeys()
.
The difference of mapSpread()
from map()
and mapWithKeys()
methods is the parameter passed to the callback function. Instead of passing a single value for each element in the Collection, mapSpread()
will pass in multiple arguments corresponding to the values of each element in the Collection.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $users = collect([ ['name' => 'John', 'age' => 25], ['name' => 'Mary', 'age' => 30], ['name' => 'Bob', 'age' => 35], ]); $users = $users->mapSpread(function ($name, $age) { return "{$name} is {$age} years old."; }); $users->all(); //Kết quả [ [0] => John is 25 years old. [1] => Mary is 30 years old. [2] => Bob is 35 years old. ] |
- mapToGroups($callback) in Laravel Collection is used to transform a Collection into an array grouped by a specific property.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $students = collect([ ['name' => 'John', 'gender' => 'male', 'class' => 'A'], ['name' => 'Jane', 'gender' => 'female', 'class' => 'A'], ['name' => 'Bob', 'gender' => 'male', 'class' => 'B'], ['name' => 'Alice', 'gender' => 'female', 'class' => 'B'] ]); $studentsByClass = $students->mapToGroups(function ($item, $key) { return [$item['class'] => $item]; }); dd($studentsByClass->all()); |
Result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | IlluminateSupportCollection {#1419 ▼ #items: array:2 [▼ "A" => IlluminateSupportCollection {#1331 ▼ #items: array:2 [▼ 0 => array:3 [▼ "name" => "John" "gender" => "male" "class" => "A" ] 1 => array:3 [▼ "name" => "Jane" "gender" => "female" "class" => "A" ] ] } "B" => IlluminateSupportCollection {#1330 ▼ #items: array:2 [▼ 0 => array:3 [▼ "name" => "Bob" "gender" => "male" "class" => "B" ] 1 => array:3 [▼ "name" => "Alice" "gender" => "female" "class" => "B" ] ] } ] } |
- mapWithKeys($callback) : in Laravel Collection allows to transform Collection values into a new key-value associative array. It uses a callback function to do this and returns a new Collection with the key-value pairs generated by the callback function.
For example :
1 2 3 4 5 6 7 8 9 10 | $products = collect([ ['name' => 'Iphone 11', 'price' => 999], ['name' => 'Samsung Galaxy S10', 'price' => 899], ['name' => 'Google Pixel 4', 'price' => 799], ]); $newArray = $products->mapWithKeys(function ($item) { return [$item['name'] => $item['price']]; }); |
Result:
1 2 3 4 5 6 7 8 | IlluminateSupportCollection {#1329 ▼ #items: array:3 [▼ "Iphone 11" => 999 "Samsung Galaxy S10" => 899 "Google Pixel 4" => 799 ] } |