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

1 year 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:


namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

        // 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);

        // 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)


Note: All Input Fields are required.