I want to sum money column from payments table:
Then, append it to every Client in index method (I’m getting all user->clients).
>Solution :
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
