DEV Community

Cover image for Zip Pdf Files And Download In Laravel
Ajay Yadav
Ajay Yadav

Posted on • Updated on

Zip Pdf Files And Download In Laravel

In this post we'll see how to create a zip file and download it in laravel.
Let's start
create a controller

php artisan make:controller InvoiceController
Enter fullscreen mode Exit fullscreen mode

Now open InvoiceController and create a method downloadZip()


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function downloadZip()
    {
        Storage::disk('local')->makeDirectory('tobedownload',$mode=0775); // zip store here
        $zip_file=storage_path('app/tobedownload/invoices.zip');
        $zip = new \ZipArchive();
        $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        $path = storage_path('invoices'); // path to your pdf files
        $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 = substr($filePath, strlen($path) + 1);
                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();
        $headers = array('Content-Type'=>'application/octet-stream',);
        $zip_new_name = "Invoice-".date("y-m-d-h-i-s").".zip";
        return response()->download($zip_file,$zip_new_name,$headers);
    }
}


Enter fullscreen mode Exit fullscreen mode

Here we are using ZipArchive() class , you can read more about this on this link

Now create a route, open web.php

//web.php
use App\Http\Controllers\InvoiceController;

Route::get('/invoice-download',[InvoiceController::class, 'downloadZip']);

Enter fullscreen mode Exit fullscreen mode

And that's all... 🤗

Discussion (0)