You can use the selectRaw method to select multiple sums in a single query. Here's an example:
public function render()
{
$totals = Invoice::selectRaw("
SUM(CASE WHEN status IN ('open', 'paid', 'late') AND YEAR(invoice_date) = YEAR(NOW()) THEN total_incl ELSE 0 END) AS total_tax_incl,
SUM(CASE WHEN status IN ('open', 'paid', 'late') AND YEAR(invoice_date) = YEAR(NOW()) THEN total_excl ELSE 0 END) AS total_tax_excl,
SUM(CASE WHEN status = 'open' THEN total_incl ELSE 0 END) AS total_open_tax_incl,
SUM(CASE WHEN status = 'open' THEN total_excl ELSE 0 END) AS total_open_tax_excl,
SUM(CASE WHEN status = 'late' THEN total_incl ELSE 0 END) AS total_late_tax_incl,
SUM(CASE WHEN status = 'late' THEN total_excl ELSE 0 END) AS total_late_tax_excl,
SUM(CASE WHEN status = 'pending' THEN total_incl ELSE 0 END) AS total_pending_tax_incl,
SUM(CASE WHEN status = 'pending' THEN total_excl ELSE 0 END) AS total_pending_tax_excl,
SUM(CASE WHEN status = 'concept' THEN total_incl ELSE 0 END) AS total_concept_tax_incl,
SUM(CASE WHEN status = 'concept' THEN total_excl ELSE 0 END) AS total_concept_tax_excl
")->first();
return view('livewire.invoice.index', [
'invoices' => Invoice::with('customer')
->orderBy('invoice_date', 'desc')
->paginate($this->limit),
'totals' => $totals,
]);
}
This will generate a single query that selects all the sums you need. The CASE statements are used to conditionally sum the values based on the status and invoice date. The first() method is used to retrieve the first row of the result set, which contains the sums. You can then pass the sums to your view as a variable.