Search code examples
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.

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


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.