How to create zip file in Laravel and download

How to create zip file in Laravel and download

Laravel provides us a lots of functions and packages which makes the web development process easy and simple. Here we are also gona be use a method which help us to create a zip file. As we know zip file is a compressed file which contains more then one file in it. In this article, we will discuss about how to create zip file in Laravel and download.

Using a Laravel ZipArchive Function

ZipArchive is a Laravel builtin function which provide the ability to create a zip file which contains one ore more than on files which are text files, images or any media files. This function is the part of PHP Library. There is no need to install any other package in our project.

Here's How to create zip file in Laravel and download:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ZipHandlerController extends Controller
{
    public function downloadZip(Request $request){
        $zip_file = 'newzip.zip';

        // PHP class installing
        $zip = new \ZipArchive();
        $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

        $invoice_file = 'mypdf/tss1.pdf';

        $zip->addFile(storage_path($invoice_file), $invoice_file);
        $zip->close();

        // return download
        return response()->download($zip_file);
    }
}

Comments

No Comment posted Yet!

Leave a Reply

OK! You can skip this field.