Support the ongoing development of Laravel.io →
Database Eloquent

Hey Guys,

i want to create a small invoicing software for my company using laravel and, of course, eloquent. I'm a little stuck in creating the proper models and connecting them.

I have 2 mysql tables: 'invoices': holding basic details about an invoice, like client_id, dates, etc. 'invoices_items': holding all the item of an invoice, described by title, description, a price field and a quantity field

What i want to do now is, whenever i get one or more invoices from the database, the total of the invoice should automatically be calculated and appended to the invoice.

So i want to use a "/sales/month" method to get the sum of all invoices of the current month. By now, i solved this by getting the invoices first, than getting the positions, looping through them to calculate totals and return the total. But is that the right way to use eloquent or is there a easier, more maintainable and more performant way to do that?

Thanks for your help! Chris

Last updated 3 years ago.
0
$sum = 0;

foreach($invoices as $invoice) 
{
    $sum += $invoice->items->sum('price');
}
Last updated 9 years ago.
0

Thanks for your answer. I considered this, but the prices of the invoice items also need to be multiplied by their quantity.

So how would i do this? Can I multiply directly in the sum function?

$sum += $invoice->items->sum('price * quantity');

Thanks Chris

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.