Created
October 9, 2025 16:10
-
-
Save ziadoz/9a4f039506e4ccda5374561ee72b087d to your computer and use it in GitHub Desktop.
Laravel 12.x - Download Zip of Multiple Files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DownloadController extends Controller | |
{ | |
public function download(Queue $queue): StreamedResponse | |
{ | |
$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); | |
}); | |
// Could add caching headers, route rate limiting etc. to improve overall performance. | |
return response()->streamDownload( | |
fn () => fpassthru(fopen($tmpPath, 'rb')), | |
'your-files.zip', | |
['Content-Type' => 'application/zip'], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment