'Laravel 8 Sum column of related table

I have 2 tables, 'Invoice table', and related 'linesInvoice' table.

To simplify it, I will say that the invoice lines table has only the invoice_id field for the relationship and total for the price.

Now, I need to get last invoices, with his totals (totals, is the sum of column 'total' in every line). I've tried many examples, but none works for me correctly.

Controller:

$lastInvoices = Invoice::latest()
                          ->limit(10)
                          ->with(['invoiceLines'])->get();

Model for relation

public function invoiceLines()
{
    return $this->hasMany(InvoiceLines::class, 'invoice_id');
}

The result that I want for example looks like:

[
  Invoice_id => 1
  total => 500 //Sum of totals in lines of invoice 1
],
[
  Invoice_id => 2
  total => 300 //Sum of totals in lines of invoice 2
],

I guess I could go through all the invoices and lines in foreachs and make the sum. But I hope it can be done in the same query



Solution 1:[1]

Laravel 8^

Invoice::with('invoiceLines')->latest()->first()->invoiceLines()->sum('totle');

totle colme table invoiceLines

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ali hassan