To calculate the sum of values in a numeric collection using Illuminate/Collections in Laravel, you can use the sum()
method.
Here is an example of how to calculate the sum:
use Illuminate\Support\Collection;
$collection = collect([1, 2, 3, 4, 5]);
$total = $collection->sum();
echo $total;
Output:
15
You can also use the sum()
method with a callback function to perform calculations on nested values or object properties:
use Illuminate\Support\Collection;
$collection = collect([
['name' => 'John', 'age' => 20],
['name' => 'Jane', 'age' => 25],
['name' => 'Sam', 'age' => 30],
]);
$totalAge = $collection->sum(function ($item) {
return $item['age'];
});
echo $totalAge;
Output:
75
In the above example, the callback function returns the 'age' value from each item, and the sum()
method calculates the total age.