How to Make a Zip File and Download It in Laravel

Hello Geek, If you need users to be able to download multiple files at once, it is preferable to create a single archive and allow them to download it. The Laravel method is demonstrated here.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ZipController extends Controller
{
    public function downloadZip(Request $request){
        $zip_file = 'invoices.zip';

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

        $invoice_file = 'invoices/AMZ-001.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);
    }
}

That’s all.

All the best nerd!

Leave a Reply