How To Create Zip File In Laravel 8

In this article, we will see example of how to create a zip file in laravel 8. Sometimes clients have requirements to have functionalities like creating zip files for documentation or images and downloading them. So, using ziparchive function you can create a zip file and download it in laravel 8.

In this example, we will see how to create a zip file in laravel using ziparchive without any package. Laravel provides ZipArchive class for creating zip files in laravel. So, we will use ZipArchive in laravel 8 and create a zip file.

So, let's see create and download a zip file using ziparchive in laravel 8.

Read More Official Document of PHP: ZipArchive

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

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

 

Step 1: Add Route

In this step, we will add a route. So, add the below code in the web.php file.

routes/web.php


<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ZipController ;

Route::get('ziparchive_example', [ZipController ::class, 'ZipArchiveExample']);

 

 

Step 2: Create Controller

Now, we will create a controller and add the function ZipArchiveExample.

app/Http/Controllers/ZipFileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use ZipArchive;

class ZipController extends Controller
{
    public function ZipArchiveExample()
    {                                
        $zip = new ZipArchive;

        $fileName = 'Zipfile_example.zip';

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

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

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

Now, run the below command in your terminal.

php artisan serve

 

 

Now you can open the below URL on your browser:

http://localhost:8000/ziparchive_example

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS