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
$sum = 0;
foreach($invoices as $invoice)
{
$sum += $invoice->items->sum('price');
}
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
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community