Sum of relations in Laravel


How to get the sum of relationships in eloquent? Let’s look into that with an example.

Suppose you are working on a e-shopping project and have a cart table which has id, user_id, product_id and timestamps. User can store multiple products so user model has many carts. Cart model belongs to user and it has many products in it. To count all products we can do count().

Auth::user()->cart()->count()

To get the sum of prices of all products in the users cart use

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

Or

$sum = Auth::user()->cart()->products()->sum('price');

You have to add the products table to the relationship. Cart model is the pivot table here.

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

It is handled in User and Product models. The Auth knows which user logs in.