PASSWORD RESET

Your destination for complete Tech news

How to calculate the sum of items in a Laravel Collection?

2.04K 0
< 1 min read

To calculate the sum of the items in a Laravel collection, you can use the sum method. This method will return the sum of the items in the collection.

Here’s an example:

$collection = collect([1, 2, 3, 4, 5]);
$sum = $collection->sum();

// $sum is now 15

You can also pass a callback to the sum method to specify a custom calculation function:

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$sum = $collection->sum(function ($item) {
    return $item['age'];
});

// $sum is now 90

If you want to calculate the sum of a specific key of the items in the collection, you can use the pluck method to extract the values before calling the sum method:

$collection = collect([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 35],
]);

$sum = $collection->pluck('age')->sum();

// $sum is now 90

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.