Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel 8 – Insert column of sums of child's columns and show it

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading