How To Create Zip File Using Ziparchive in Laravel

WebSolutionStuff | Sep-16-2020 | Categories : Laravel

In this tutorial i will show you how to create zip file using ziparchive in laravel. Some times client's have requirments to have functionalities like create zip file for documantation or images and download it.

So, at that time we can find many laravel packeges to perform this task. But here, i am show you to how to create zip file in laravel using ziparchive without any packege. Laravel provide ZipArchive class for create zip file in laravel,So i will use ZipArchive in laravel.

In below code i have created one function in laravel controller and added ZipArchive class.

Note : I have created  Zip_Example folder in public folder and added some images , So you need to also create one folder and  add some file also.

 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use ZipArchive;

public function ZipArchiveExample()
{                                
    $zip = new ZipArchive;

    $fileName = 'Example.zip';

    if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
    {
        $files = \File::files(public_path('Zip_Example'));

        foreach ($files as $key => $value) {
            $file = basename($value);
            $zip->addFile($value, $file);
        }
         
        $zip->close();
    }

    return response()->download(public_path($fileName));
}

 

Featured Post



Follow us
facebooklogo github instagram twitter