How to Create Zip File and Download in Laravel - Techvblogs

How to Create Zip File and Download in Laravel

Learn how to create zip file and download in Laravel easily with this step-by-step guide for efficient file management.


Suresh Ramani - Author - Techvblogs
Suresh Ramani
 

2 days ago

TechvBlogs - Google News

It is preferable to make one archive and allow users to download it if you require them to be able to download many files at once. The laravel method is shown here.

Actually, we will be utilizing the ZipArchive class, which has been there since PHP 5.2, It's less about Laravel and more about PHP. To utilize it, confirm that the ext-zip extension is enabled in your php.ini.

How to Create Zip File and Download in Laravel

Here's the code:

<?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 it.

Thank you for reading this article.

Read Also: How To Count Days Between Two Dates in Laravel

Comments (0)

Comment


Note: All Input Fields are required.