Hello Artisan
Now i am going to start a new series on laravel collection.In this series, we take a look at each of the available methods in the Laravel Collection class and dive deep through examples in explaining what it does.
I am going to create a tutorial on every collection method. The Illuminate\Support\Collection
class provides a fluent, convenient wrapper for working with arrays of data.
Collection
class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. Now in this first laravel collection tutorial i am going to discuss about average() and the alias avg(). So let's have a look
Example 1 : average()
Let's think we have a simple array and we would like to find out the average value from this array. How we can do it using laravel collection. Let's have a look on the below example.
Route::get('/', function () {
$data = [
10,
20,
30
];
return collect($data)->average();
});
For example, check out the following code. We'll use the collect
helper to create a new collection instance from the array.
Look, we have a data property object and we just push it into laravel collection collcet() helper method and just call the average function. What will be the output?
//output
20
Example 2 : average()
We can also pass parameter to average function. see example.
Route::get('/', function () {
$data = [
["price" => 10],
["price" => 20],
["price" => 30]
];
return collect($data)->average("price");
});
Ourput will be the same.
Example 3 : average()
Now have a look on a little bit advance query. Think we have to property in an array We have to find out specific average from single field and then we have to add those average. How can we do that ? See the below example.
Route::get('/', function () {
$data = [
["price" => 10, "tax" => 5],
["price" => 20, "tax" => 10],
["price" => 30, "tax" => 15]
];
return collect($data)->average(function($value) {
return $value["price"] + $value["tax"];
});
});
//Output
30
Output will be 30. because from price we get 20 average and from tax we get 10 average and then finally we have to add it. So we have passed a closer to average function with value parameter and then add it.
Example 4 : average()
Now we will add one more field like active. So we only find out the average of active field and then finally add it. See the below example
Route::get('/', function () {
$data = [
["price" => 10, "tax" => 5, "active" => false],
["price" => 20, "tax" => 10, "active" => false],
["price" => 30, "tax" => 15, "active" => true]
];
return collect($data)->average(function($value) {
return !$value['active']
? null : $value["price"] + $value["tax"];
});
});
//output
45
Output will be 45. because from price we get 30 average and from tax we get 15 average and then finally we have to add it.
So we have passed a closer to average function with value parameter and then add it. Here we find out only active filed average and add it finally.
#laravel #laravel-collection #collection #average #avg