Create multiple Zip Files and Download in Laravel application
In Laravel, you can create multiple zip files and download them using the built-in “ZipArchive” class and the “File” facade.
- Use the “File” facade to create the zip files. For example:
use File;
class MyController extends Controller {
public function download() {
$files = [
public_path('file1.txt'),
public_path('file2.txt'),
public_path('file3.txt'),
];
$zipName = 'files.zip';
$zip = new ZipArchive;
$zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
}
}
2. Use the “response()->download()” method to send the zip file to the user. For example:
class MyController extends Controller {
public function download() {
$files = [
public_path('file1.txt'),
public_path('file2.txt'),
public_path('file3.txt'),
];
$zipName = 'files.zip';
$zip = new ZipArchive;
$zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
return response()->download($zipName);
}
}