Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active October 16, 2025 11:07
Show Gist options
  • Save ziadoz/9a4f039506e4ccda5374561ee72b087d to your computer and use it in GitHub Desktop.
Save ziadoz/9a4f039506e4ccda5374561ee72b087d to your computer and use it in GitHub Desktop.
Laravel 12.x - Download Zip of Multiple Files
<?php
class DownloadController extends Controller
{
public function download(Request $request): StreamedResponse
{
$filename = 'unique-filename.zip';
$checksum = base64_encode(hash('xxh128', $filename, true));
if (in_array($checksum, $request->getETags())) {
abort(304);
}
$tmpPath = stream_get_meta_data(tmpfile())['uri'];
$zip = new ZipArchive;
$zip->open($tmpPath, ZipArchive::CREATE);
foreach ($files as $filePath) {
$zip->addFromString(basename($filePath), Storage::disk('cloud')->get($filePath));
}
$zip->close();
// Delete the temp file after the request has been served.
defer(function () use ($tmpPath) {
@unlink($tmpPath);
});
return response()->streamDownload(
fn () => fpassthru(fopen($tmpPath, 'rb')),
$filename,
['Content-Type' => 'application/zip', 'ETag' => $checksum],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment