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.

  1. 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);
    }
}

Anil Bajracharya

Developer,a tech enthusiastic who's passionate about learning new technology and programming Find me on linkedin linkedin

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *