Laravel comes with very powerful and convenient wrapper for working with arrays. You must have used collections in Laravel specially while working with Eloquent. Eloquent returns the query results in custom Collection object ~ Eloquent Collection class is inherited from Laravel Collections therefore, it inherits all the powerful methods offered by Laravel Collection and on top, provides few more great methods to use.
In this article, we will review some of the best and must-know Laravel Collection methods to make your life easier working with Laravel.
_ Note : Remember, Eloquent Collection inherits Laravel Base Collection class thus it has access to all of the Base Collection's methods but Base Collection object cannot access custom methods provided by eloquent collection. _
Let's look at how you can create simple Laravel Base Collection Object:
$todocollection = collect([
[
'user_id' => '1',
'title' => ‘Do Laundry,
‘description => ‘I ‘have to do laundry ‘
],
[
'user_id' => '1',
'title' => ‘Finish Assignment,
‘description => ‘I have to finish Maths assignment ‘
],
]);
This is how you can create Laravel Collection object. You can use all the powerful methods provided by Laravel Collection.
Now, let's look at an example of Eloquent Collection object:
$todos = ToDo::where('user_id',1)->get();
Here, $todos is an eloquent collection object which contains query results. It is simply an array from inside with some powerful collection methods at your disposal. You can still use Laravel Collection methods but Eloquent Collection also provides additional methods. You can do various things like converting to array, filtering your collection, sorting, mapping etc.
Let's look at some of the best and must-know Laravel Collection Methods:
1) all()
Laravel Collection class has a protected property called $items which contains an array with all the data. Collection wrapper provides additional methods to operate on that array. But if you simply want the array without all those bells and whistles then there is a method for that!
$emails = collect([
‘abc@gmail.com,
‘user@yahoo.com’,
‘example@example.com’,
‘test@yahoo.co.in’
]);
$emails_array = $emails->all();
dd($emails_array);
/*
Array:4 [▼
0 => "‘abc@gmail.com"
1 => "user@yahoo.com"
2 => "example@example.com’"
3 => “test@yahoo.co.in”
]
*/
2) avg()
Avg method provided by Laravel Collection returns the average value. By default, it will provide average of all the values in collection. But, if collection contains key => value pair, then you can provide key to the function and it will automatically calculate the average of all values to that key.
$simple_collection = collect([2,5,7,35,25,10]);
$s_avg = $simplex_collection->avg();
// 14
$key_collection = collect(['score' => 98], ['score' => 90], ['score' => 70],['score' => 86]);
$key_avg = $key_collection->avg();
//86
3) each()
Each method for Laravel Collection is similar to map function on arrays in PHP and JavaScript. Each method basically takes each element from the collection and applies the callback function on it. This method can be used to apply operations on each element, modify each element etc.
$collection = collect([1,2,3,4]);
$collection->each(function($item){
return $item*$item;
});
// [1,4,9,16]
4) chunk()
chunk() method is used to split the Laravel Collection into multiple chunks of a given size.
$users = User::all();
$userschunk = $users->chunk(2);
dd($userschunk->toArray());
array:3 [▼
0 => array:2 [▼
0 => array:3 [▼
"id" => 1
"name" => "John Doe"
"email" => "johndoe@example.com"
]
1 => array:3 [▼
"id" => 2
"name" => "Jack Halt"
"email" => "jhalt@example.com"
]
]
1 => array:1 [▼
2 => array:3 [▼
"id" => 3
"name" => "Sam Pitt"
"email" => "spitt@example.com"
]
]
]
*Also Read: *
- Laravel 7 Tutorial for Beginner: Create your First To-Do App
- How to Schedule tasks with cron jobs using Laravel Scheduler
5) contains()
Often, you will need to check whether a collection contains a value or not. The Laravel Collection provides easy method to check that.
The contains() function is used to check whether the laravel collection contains the value passed to it as a parameter. It will return a boolean value -- true if it contains and false if not.
$users = collect(['name' => 'John Doe', 'email' => "johndoe@example.com"]);
$users->contains('johndoe@example.com');
// true
$users->contains('spitt@example.com');
// false
It can also accept pair of key and value for more granular search. It will check whether the given pair exists or not.
$users = collect(['name' => 'John Doe', 'email' => "johndoe@example.com"]);
$users->contains('email', 'johndoe@example.com');
// true
$users->contains('name', 'johndoe@example.com');
// false
You can also pass a callback function with your own condition to check whether any value passes the given condition.
$collection = collect([11, 25, 30, 45, 50]);
$collection->contains(function ($value, $key) {
return $value == 55;
});
// false
The contains() method will use loose comparison to apply the condition. For more strict comparison, you can use _*containsStrict() *_method.
6) count() & countBy()
This is very simple yet very helpful method provided by Laravel Collection. How many times you need to count the items in Laravel Collection or an array?
The Count() method gives the total number of items in given Laravel Collection.
$collection = collect([10,20,30,40,50]);
$collection->count();
// 5
Laravel collection also provides more advanced method to count its items.
The CountBy() method gives the count of item's occurrences in given Laravel Collection in array.
$numbercollection = collect([10, 30,30, 50, 50]);
$counts = $numbercollection->countBy();
$counts->all();
// [10 => 1, 30 => 2, 50 => 2]
7) filter()
The _filter() _method is one of the most popular and useful Laravel Collection method. It allows you to filter your collection using the passed callback function. It returns the new collection with filtered items and does not change the original collection.
The callback function is provided with _ key ** __and **value _ as its parameters which you can utilize to create the filter condition.
$users = collect(['name' => 'John Doe', 'email' => "johndoe@example.com"]);
$filter = $users->filter(function($value, $key) {
if ($value['email'] == "johndoe@example.com") {
return true;
}
});
$filter->all();
/*
[
1 =>[
'name' => 'John Doe',
'email' => "johndoe@example.com"
]
]
*/
If you don't provide any callback function, then it will simply remove any items equivalent to _ false __. _So, values like **null, false, ", 0, [] **will be filtered out. This method is easiest way to weed out any empty items in the collection.
8) get()
get()_ _is a method which returns the value at the key you pass to it as a parameter. If no key is passed then null is returned.
$users = collect(['name' => 'John Doe', 'email' => "johndoe@example.com"]);
$value = $users->get('name');
// John Doe
9) search()
search()_ _is another small yet helpful Laravel Collection method. It searches the Collection for the given value and returns the index if found. If it's not found then false will be returned.
$numbers = collect([31,21,53,64,27]);
$numbers->search(27);
// 4
10) groupBy()
Often you will need to group the data as per certain data. Normally, you would group at database level, but still there are many use-cases where you might need to further group the data in collection.
Laravel Collections offer handy method just for that. It works similar to Eloquent's groupBy and groups the items by given key.
$orders = collect([
['product_id' => 'p10', 'email' => 'jdoe@example.com'],
['product_id' => 'p10', 'email' => 'billy@example.com'],
['product_id' => 'p11', 'email' => 'danny@example.com'],
]);
$grouped = $orders->groupBy('product_id');
$grouped->toArray();
/*
[
'p10' => [
['product_id' => 'p10', 'email' => 'jdoe@example.com'],
['product_id' => 'p10', 'email' => 'billy@example.com'],
],
'p11' => [
['product_id' => 'p11', 'email' => 'danny@example.com'],
],
]
*/
11) max()
In Excel, you may used this function many times to get the maximum value in a column or row. Similarly, Laravel Collections provides **max() **function to get the maximum value of given key among collection items.
$counter = collect([['count' => 10], ['count' => 20]]);
$counter->max('count');
// 20
If you don't pass any key to max() function, it will simply compare each item and return the highest one.
12) pluck()
pluck() is one of my favourite and most used method for Laravel Collection and more frequently for Eloquent Collection. It allows us to fetch values for given key from the collection in array.
$users = collect([
['name' => 'John Doe', 'email' => "johndoe@example.com"],
['name' => 'Jack Sparrow', 'email' => "sparrow@example.com"]
]);
$emails = $users->pluck('email');
/*
["johndoe@example.com","sparrow@example.com"]
*/
13) forget()
forget() is a laravel collection method which simply removes given key and its value from all the items in the collection.
$users = collect(['name' => 'John Doe', 'email' => 'johndoe@example.com']);
$users->forget('name');
$users->all();
// ['email' => 'johndoe@example.com']
14) toArray()
**toArray() **is a straightforward Laravel Collection method to convert your collection object to a plain php array.
$users = collect(['name' => 'John Doe', 'email' => 'johndoe@example.com']);
$users->toArray();
/*
[
['name' => 'John Doe', 'email' => 'johndoe@example.com'],
]
*/
15) sortBy()
sortBy() is a very helpful method to sort your Laravel Collection by given key. It retains the original keys, just reorders the items in the collection as per the sorting condition.
$products = collect([
['name' => 'Laptop', 'price' => 2000],
['name' => 'Mouse', 'price' => 100],
['name' => 'Keyboard', 'price' => 150],
]);
$sortedproducts = $products->sortBy('price');
/*
[
['name' => 'Mouse', 'price' => 100],
['name' => 'Keyboard', 'price' => 150],
['name' => 'Laptop', 'price' => 2000],
]
*/
For more advanced sorting, you can also pass a callback function which will handle how to sort the items.
In a nutshell, these are best Laravel Collections methods you must know as a Laravel developer. There are lot more methods offered by Laravel Collections which you can checkout at Laravel Documentation.
The post 15 Must know Laravel Collection Methods ~ Laravel Collections Tutorial appeared first on Parth Patel - a Web Developer.
Top comments (1)
Thank you for these Parth!