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.
Here's an example of how you can use it:
<?php
$users = App\User::with('orders')
->whereHas('orders', function ($query) {
$query->where('status', 'completed');
})
->get();
foreach ($users as $user) {
$totalAmount = $user->orders->sum('amount');
}
Watch a video course
Learn object oriented PHP
This will give you the sum of the amount
column for all of the completed
orders of each user.
Keep in mind that this will execute a separate query for each user to retrieve their orders, so it may not be very efficient if you have a large number of users. In that case, you may want to use a more efficient solution such as using a subquery or joining the tables.