Recursively Download Multiple Files as Zip File in Laravel

Hello Artisan,

In this tutorial, I will explain about how to download multiple files as a zip file using laravel. So in this laravel 8 ziparchive tutorial, you will learn how to download files recursively in laravel. 

That means, assume we have a folder there is a bunch of files. So now we will download all of those folders one by one recursively in Laravel application. So if you don't know how to do laravel create a zip file and download them recursively, then this example is for you.

To create this zip file recursively, we don't need any packages. Cause PHP provides ZipArchive to create a zip folder and download. So let's start:

 

Step 1: Add Route

In the first step, we have to create a route to show simple Create ZIP Button. So let's add it

routes/web.php

Route::get('zip-download', 'App\Http\Controllers\ProductController@zipDownload')->name('zip-download');

 

Step 2: Create Download Zip Button

In this step, we will create a download zip button. So add this code where you want to show the download zip button.

 

Step 3: Create Controller

Now to create laravel zip folder and download system, we need to implement our code. We will download files recursively. So update your controller like below:

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use File;
use ZipArchive;

class ZipArchiveController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function zipDownload(Request $request)
    {
      if($request->has('download')) {
            $zip      = new ZipArchive;
            $fileName = 'attachment.zip';
            if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE) {
              $files = File::files(public_path('uploads/file'));
              foreach ($files as $key => $value) {
                $relativeName = basename($value);
                $zip->addFile($value, $relativeName);
              }
              $zip->close();
            }
            return response()->download(public_path($fileName));
        }

    }
}

 

Read also: How to Fix Cross Site Scripting Vulnerability in Laravel

 

Make sure, your all files are located in uploads/file directory. Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js