Create Zip File and Download in Laravel

 

Creating a Zip File using the `ZipArchive` class and downloading it in Laravel is a common task for bundling multiple files into a single compressed archive. Here's how you can achieve this:


1. Prepare Your Files:

   Make sure you have the files you want to include in the zip archive available in a directory.


2. Create a Route and Controller:

   Define a route in your `routes/web.php` file to trigger the creation and download of the zip file:


   Route::get('/download-zip', 'ZipController@downloadZip');


   Next, create a controller by running the command:


   php artisan make:controller ZipController


3. Edit the Controller:

   Open the `ZipController.php` file in your `app/Http/Controllers` directory. In the `downloadZip` method, add the following code:


   public function downloadZip()

   {

       $zip = new \ZipArchive;

       $zipFileName = 'files.zip'; // Desired name of the zip file

       $zipFilePath = public_path($zipFileName);


       if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {

           $filesToZip = [

               'path/to/file1.txt',

               'path/to/file2.jpg',

               // Add other files to include in the zip

           ];


           foreach ($filesToZip as $file) {

               $zip->addFile($file, basename($file));

           }


           $zip->close();


           return response()->download($zipFilePath)->deleteFileAfterSend(true);

       } else {

           return response('Failed to create the zip file.', 500);

       }

   }


4. Create the Zip Files Directory:

   In your Laravel project's `public` directory, create a directory named `zipfiles` to store the generated zip files.


5. Update .env File:

   Make sure you have the `APP_URL` setting in your `.env` file correctly set to your application's URL.


6. Usage:

   Visit the `/download-zip` route in your browser, and the zip file will be generated and downloaded automatically.


Remember to replace `'path/to/file1.txt'`, `'path/to/file2.jpg'`, and other paths with the actual paths of the files you want to include in the zip archive.


That's it! With these steps, you've set up the functionality to create and download zip files using the `ZipArchive` class in your Laravel application.