public function getInvoiceDocumentsZip($invitationKey) { if (!($invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey))) { return $this->returnError(); } Session::put('contact_key', $invitation->contact->contact_key); // track current contact $invoice = $invitation->invoice; $toZip = $this->getInvoiceZipDocuments($invoice); if (!count($toZip)) { return Response::view('error', ['error' => 'No documents small enough'], 404); } $zip = new ZipArchive($invitation->account->name . ' Invoice ' . $invoice->invoice_number . '.zip'); return Response::stream(function () use($toZip, $zip) { foreach ($toZip as $name => $document) { $fileStream = $document->getStream(); if ($fileStream) { $zip->init_file_stream_transfer($name, $document->size, ['time' => $document->created_at->timestamp]); while ($buffer = fread($fileStream, 256000)) { $zip->stream_file_part($buffer); } fclose($fileStream); $zip->complete_file_stream(); } else { $zip->add_file($name, $document->getRaw()); } } $zip->finish(); }, 200); }