How to Create Zip File and Download in Laravel - TechvBlogs

How to Create Zip File and Download in Laravel

In this article, We will learn How to Create Zip File and Download in Laravel.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

2 months ago

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

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

Comments (0)

ServerAvatar
Multiple sites on a single VPS/VM/Server Deploy PHP sites on cloud in minutes, simple as that!
ServerAvatar
Generate Free SSL Certificate - SSLForWeb

Generate Free SSL Certificate

  • 90-Day Certificates
  • SSL Monitoring
  • Wildcard Certificates
  • Multiple Domains
  • Certificate Management
  • Expiration Reminders

Comment


Note: All Input Fields are required.