Laravel - Collections - Method Sum

The sum method returns the sum of all items in the collection:

    
    collect([1, 2, 3, 4, 5])->sum();
    
    // 15
	

If the collection contains nested arrays or objects, you should pass a key that will be used to determine which values to sum:

    
    $collection = collect([
        ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
        ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
    ]);
    
    $collection->sum('pages');
    
    // 1272
	

In addition, you may pass your own closure to determine which values of the collection to sum:

    
    $collection = collect([
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]);
    
    $collection->sum(function ($product) {
        return count($product['colors']);
    });
    
    // 6