The Laravel framework comes with very powerful wrapper for working with arrays - Collections. If you have worked with Eloquent you must have encountered and used Collections. Collections are a broader term, where Eloquent Collections are the implementation of these broader Collections. The methods that we cover in this article can be used for both instances.
Table of Contents
Prerequisites
To follow this guide, you will need the following components:
- PHP 8.1
- Composer (installed globally)
- install package illuminate/collections
Also if you would want to learn how to use Collections outside Laravel, check this article.
Now let's take a look at the 15 useful methods that you have to know when working with Laravel Collections.
Laravel Collection Methods
all() method
all()
is a method that returns all of the items in the collection.
$fruits = collect(["apples", "oranges", "strawberries"]);
$fruits->all();
// ["apples", "oranges", "strawberries"]
If you try to output the result from the $fruits->all()
function, you will notice that the output will be an array that contains all of the fruits.
count() method
Collection also has the count() method, which is a very simple method that gives the total number of items in a given collection.
$fruits = collect(["apples", "oranges", "strawberries"]);
$fruits->count(); // 3
The count()
function uses the PHP count() function to count the items in the array.
filter() method
The filter()
method allows you to filter the collection using a callback function. As a result returns new collection with filtered items and does not change the original collection.
collect([1, 2, 3, 4, 5, 6, 7])->filter(function ($value, $key) {
return $value % 2 !== 0;
})->all();
// [1, 3, 5, 7]
If there is no callback supplied, all of the items in the collection that are equals to false will be remove.
collect([1, null, 5, 7, 19, null, 24, false, '', 0, [], 50])->filter()->all();
// [1, 5, 7, 19, 24, 50]
where() method
The where()
method is a useful method if you need to filter the collection by a given key / value pair.
$plants = collect([
["type" => "flowers", "name" => "rose"],
["type" => "flowers", "name" => "tulip"],
["type" => "trees", "name" => "pine"],
["type" => "trees", "name" => "birch"]
]);
$filtered = $plants->where("type", "flowers");
$filtered->all();
// [["type" => "flowers", "name" => "rose"],["type" => "flowers", "name" => "tulip"]]
each() method
To iterate over items in the collection you can use the each()
method. The method passes each item to a closure. Returning false will stop iterating through the items.
$collection = collect([]);
collect([1, 2, 3, 4, 5, 6, 7])->each(function ($value, $key) use ($collection) {
if($value >= 5){
return false;
}
$collection->push($value);
});
// [1, 2, 3, 4]
first() method
When working with collection, often you will encounter a task where you have to return the first item. Here handy comes the method first()
, which returns the first element in the collection, or returns null whether the collection is empty.
$fruits = collect(["apples", "oranges", "strawberries"]);
$fruits->first(); // "apples"
The first method also accepts closure function that returns the first element in the collection that passes a certain truth test.
collect([1, 2, 3, 4, 5, 6, 7])->first(function ($value, $key) {
return $value > 5;
}); // 6
last() method
The method last()
returns the last element in the collection or a null if the collection is empty.
$fruits = collect(["apples", "oranges", "strawberries"]);
$fruits->last(); // "strawberries"
As with the method first()
, the method last()
also accepts a function that returns the last element in the collection that passes a certain truth test.
collect([1, 2, 3, 4, 5, 6, 7])->last(function ($value, $key) {
return $value > 5;
}); // 7
pluck() method
The method pluck()
is maybe one of my most used method when I'm working with Laravel Collections. It's very easy and convinient to use when I want to get the values for a given key from the collection in array.
$plants = collect([
["type" => "flowers", "name" => "rose"],
["type" => "flowers", "name" => "tulip"],
["type" => "trees", "name" => "pine"],
["type" => "trees", "name" => "birch"]
]);
$plucked = $plants->pluck("name");
$plucked->all(); // ['rose', 'tulip', 'pine', 'birch']
Another way to retrieve the nested values with pluck()
is to use "dot" notation.
$plants = collect([
[
"family" => "Rosaceae",
"list" => [
"plants" => ["firethorn", "cloudberry"],
"fruits" => ["plum", "blackberry"]
],
],
[
"family" => "Liliaceae",
"list" => [
"plants" => ["lily", "tulip"],
]
],
[
"family" => "Asteraceae",
"list" => [
"plants" => ["stevia", "daisy", "marigold"],
"herbs" => ["tarragon"]
]
],
[
"family" => "Pinaceae",
"list" => [
"plants" => ["evergreen", "perennial"],
"trees" => ["hemlock", "golden larch", "fir"]
],
]
]);
$plucked = $plants->pluck("list.plants");
$plucked->all();
// [["firethorn", "cloudberry"], ["lily", "tulip"], ["stevia","daisy","marigold"], ["evergreen","perennial"]]
isEmpty() method
If you want to check whether the Collection is empty, you can use the isEmpty()
method, that returns true if the Collection is empty and false otherwise.
collect([])->isEmpty(); // true
collect([1,2,3])->isEmpty(); //false
contains() method
The contains()
method can be used when you want to check if the collection contains a given item.
$even_numbers = collect([1, 3, 6, 11, 37, 45, 67, 89]);
$even_numbers->contains(function ($value, $key) {
return $value % 2 === 0;
}); // true
Also the contains()
method accepts a closure to determine whether an element exists in the collection matching a given truth test.
$flowers = ["rose", "tulip", "daisy"];
$flowers->contains("rose"); // true
$flowers->contains("orchid"); // false
Another interesting fact is that the some()
method is actually the alias for contains()
method. Using either one will provide with the same results.
toArray() method
The method toArray()
does what the name suggests. It converts your Laravel Collection to a plain PHP array.
$dog_breeds = collect(["basenji", "beagle", "border collie", "bichon frise", "schnauzer"]);
$dog_breeds->toArray();
// ["basenji", "beagle", "border collie", "bichon frise", "schnauzer"]
has() method
The has()
method is a useful method to determine if an item exists in the collection.
$user = collect([
"name" => "John",
"surname" => "Doe",
"age" => 25,
]);
$user->has("name"); //true
$user->has("address"); //false
get() method
The get()
method is used to retrieve an item from the collection by providing a key. The method will return null if the key doesn't exist. You can also provide default value as a second argument.
$project = collect(["name" => "Weather API", "technology" => "PHP", "developer" => "John Doe"]);
$project->get("name"); // Weather API
$project->get("deadline", "2023-06-04"); // 2023-06-04
Another way to use the method is to pass a callback function that will be executed if the provided key doesn't exist in the collection.
$project->get("deadline", function() {
return "2023-06-04";
}); // 2023-06-04
map() method
The map()
method is a convenient method to use when you need to iterate through a collection, modify the items and return a new collection.
$numbers = collect([10, 100, 1000, 10000, 100000]);
$new = $numbers->map(function ($item, $key) {
return $item - 1;
});
$new->all(); // [9, 99, 999, 9999, 99999]
forget() method
When using the Laravel Collections, sometimes you would want to simply remove a given key and its value from the items in the Collection. To do that, you can use the forget()
method.
$items = collect(["vegetable" => "tomato", "fruit" => "apple", "tree" => "pine"]);
$items->forget("fruit");
// ["vegetable" => "tomato", "tree" => "pine"]
Conclusion
In this article we covered 15 useful methods that you will encounter when using the Laravel Collections. There are a lot more available methods that you can dive deeper in the official Laravel documentation.
The code in this article is available at my Github.