phplaraveleloquentrelation

Laravel Eloquent Sum of relation's column


I've been working on a shopping cart application and now I've come to the following issue..

There is a User, a Product and a Cart object.

Now to calculate the total products I can just call: Auth::user()->cart()->count().

My question is: How can I get the SUM() of prices (a column of product) of the products in cart by this User?
I would like to accomplish this with Eloquent and not by using a query (mainly because I believe it is a lot cleaner).


Solution

  • Auth::user()->products->sum('price');
    

    The documentation is a little light for some of the Collection methods but all the query builder aggregates are seemingly available besides avg() that can be found at http://laravel.com/docs/queries#aggregates.