W3docs

Laravel Eloquent Sum of relation's column

You can use the sum method on an Eloquent relation to get the sum of a column's values.

You can use the sum method on an Eloquent relation to get the sum of a column's values.

Here's an example of how you can use it:

Example of using sum method on an Eloquent relation to get the sum of a column's values

<?php

$users = App\Models\User::with('orders')
    ->whereHas('orders', function ($query) {
        $query->where('status', 'completed');
    })
    ->get();

foreach ($users as $user) {
    $totalAmount = $user->orders->sum('amount');
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This will give you the sum of the amount column for all of the completed orders of each user.

Keep in mind that while with('orders') eager loads the relations (avoiding the N+1 query problem), calling sum() on the collection still processes the data in PHP. For very large datasets, a database-level aggregation using Laravel's withSum() method (Laravel 9+) or a direct query join would be more efficient.