Laravel Eloquent Sum of relation's column

theAdmiral picture theAdmiral · Feb 10, 2014 · Viewed 258.2k times · Source

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

There is a User, a Product and a Cart object.
- The Cart table only contains the following columns: "id", "user_id", "product_id" and timestamps.
- The UserModel "hasMany" Carts (because a user can store multiple products).
- The CartModel "belongsTo" a User and CartModel "hasMany" Products.

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).

Answer

user1669496 picture user1669496 · Feb 10, 2014
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.