August 22, 2015 21:28

I've recently discovered how great collections are in Laravel.

No more array_summing or looping. Collections are easy to extend. First add this method to your model:

public function newCollection(array $models = [])
{
    return new TransactionCollection($models);
}

Then create the TransactionCollection class and extend it as you wish. For example:

class TransactionCollection extends Illuminate\Database\Eloquent\Collection
{
    public function total()
    {
        return $this->sum('amount');
    }
}

Now you can easily display the total of all transactions with $transactions->total()

Laravel, PHP