I want to sum money
column from payments
table:
Then, append it to every Client
in index
method (I'm getting all user->clients
).
CodePudding user response:
Eloquent has aggregate methods for relationships to do this already:
$clients = Client::where(...)->withSum('payments as sum', 'payment_money')->get();
foreach ($clients as $client) {
echo $client->sum;
}
Laravel 8.x Docs - Eloquent - Relationships - Other Aggregate Functions withSum
CodePudding user response:
$clients = Client::where('user_id', auth()->user()->id)->paginate(20);
$clients->each(function ($p) {
$p->sum = $p->payments()->sum('payment_money');
});
return compact('clients');