DEV Community

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

Posted on Edited 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... 🤗

Top comments (1)

Collapse
 
jurajchovan profile image
Juraj Chovan

hi friend,
if I want download some file, then delete it, I can use command:

return response()->download($SomeFileName)->deleteFileAfterSend(true);
Enter fullscreen mode Exit fullscreen mode

but open question is:
if I want download some file, then delete it and then redirect Laravel application to some other page/route?
What is code for this case? Can you help me pls ...