Yes, it is possible to stream multiple downloads using Livewire. One way to achieve this is by creating a Livewire component that generates and streams the PDFs one by one, and then using JavaScript to trigger the download of each PDF in turn.
Here's an example of how you could implement this:
- Create a Livewire component that generates and streams a single PDF. This component should have a public method that takes in the data needed to generate the PDF, and then streams the PDF to the browser using the
response()->streamDownload()method. Here's an example of what the component might look like:
class PdfGenerator extends Component
{
public $pdfData;
public function generatePdf()
{
$pdf = PDF::loadView('pdf.template', $this->pdfData);
return response()->streamDownload(function () use ($pdf) {
echo $pdf->output();
}, 'document.pdf');
}
public function render()
{
return view('livewire.pdf-generator');
}
}
- Create a Livewire component that contains the "Download All" button and handles the logic for triggering the download of each PDF. This component should have a public method that loops through the data for each PDF, calls the
generatePdf()method on thePdfGeneratorcomponent for each one, and then triggers the download of the PDF using JavaScript. Here's an example of what the component might look like:
class DownloadAll extends Component
{
public $pdfDataList;
public function downloadAll()
{
foreach ($this->pdfDataList as $pdfData) {
$pdfGenerator = Livewire::test(PdfGenerator::class, ['pdfData' => $pdfData]);
$pdfUrl = $pdfGenerator->generatePdf()->getTargetUrl();
$this->dispatchBrowserEvent('download-pdf', ['url' => $pdfUrl]);
}
}
public function render()
{
return view('livewire.download-all');
}
}
- Add JavaScript code to the view for the
DownloadAllcomponent that listens for thedownload-pdfevent and triggers the download of the PDF using thewindow.location.hrefmethod. Here's an example of what the JavaScript code might look like:
<script>
Livewire.on('download-pdf', function (data) {
window.location.href = data.url;
});
</script>
With these components in place, you can now use the DownloadAll component to generate and download multiple PDFs with a single click. Just pass in an array of data for each PDF to the pdfDataList property, and then click the "Download All" button. Each PDF will be generated and downloaded one by one.