items); return response()->streamDownload(function () use ($invoice, $taxes) { echo view('xml.invoice', ['invoice' => $invoice, 'options' => Option::optionsAsObject(), 'taxes' => $taxes]); }, 'test.xml', ['Content-Type' => 'application/xml']); } /** * Return a rendered xml invoice as string to build an email attachment from it for the specified resource. */ public function attachInvoice(int $id): string { $invoice = Invoice::find($id); $taxes = self::buildTaxes($invoice->items); return view('xml.invoice', ['invoice' => $invoice, 'options' => Option::optionsAsObject(), 'taxes' => $taxes])->render(); } /** * Build taxes for the given invoice items grouped by tax. */ private static function buildTaxes($items): array { $taxes = []; foreach ($items as $item) { if (!isset($taxes[$item->tax])) { $taxes[$item->tax] = ['tax' => 0, 'taxable' => 0]; } $taxes[$item->tax]['tax'] += round($item->price * $item->amount * ($item->tax / 100) * (100 - $item->discount) / 100, 2, PHP_ROUND_HALF_UP); $taxes[$item->tax]['taxable'] += $item->price * $item->amount * (100 - $item->discount) / 100; } return $taxes; } }