Home > other >  Laravel 8 - Insert column of sums of child's columns and show it
Laravel 8 - Insert column of sums of child's columns and show it

Time:01-04

I want to sum money column from payments table:

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');
  •  Tags:  
  • Related