Laravel Create Zip Archive with Files and Download it

Hello Artisans, today I’ll show you how to create zip archive with files and download it in our Laravel app without using any packages. Sometimes in our application, we want to let users download multiple files at one click, for this kind of operation it’s better to create one archive and let users download it. For achieved it we will use a ZipArchive class which is built-in since v5.2. But before using that we need to make sure that our php.ini has enabled the extension called ext-zip. So no more talk, let’s see how we can use it in our application.

We will first see how we can archive a file with ZipArchive class, see the below code

HomeController.php
<?php

namespace App\Http\Controllers;

use ZipArchive;

class FrontendController extends Controller
{
    public function index(): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        $zip_file = 'invoices.zip'; // Name of our archive to download

        // Initializing PHP class
        $zip = new ZipArchive();
        $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);

        $invoice_file = 'invoices/aaa001.pdf';

        // Adding file: second parameter is what will the path inside of the archive
        // So it will create another folder called "storage/" inside ZIP, and put the file there.
        $zip->addFile(storage_path($invoice_file), $invoice_file);
        $zip->close();

        // We return the file immediately after download
        return response()->download($zip_file);
    }
}

It’s easy right!

Now we will see how we can archive the whole list of invoices from our storage folder

See the below code snippet

HomeController.php
<?php

namespace App\Http\Controllers;

use ZipArchive;

class FrontendController extends Controller
{
    public function index(): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        $zip_file = 'invoices.zip';
        $zip = new ZipArchive();
        $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);

        $path = storage_path('invoices');
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
        foreach ($files as $name => $file)
        {
            // We're skipping all subfolders
            if (!$file->isDir()) {
                $filePath     = $file->getRealPath();

                // extracting filename with substr/strlen
                $relativePath = 'invoices/' . substr($filePath, strlen($path) + 1);

                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();
        return response()->download($zip_file);
    }
}

And you’re done. You don’t need to use any packages for that and it’s very easy to use too.

That’s all for today. Hope it can help you. Thanks for reading.