Laravel 9 Create Zip File And Download

Laravel 9 Create Zip File And Download

Hello friends, Today we will explain laravel 9 create zip file and download. In this example we will show how to create zip file and download in laravel 9. Here you will learn step by step of how to create a zip file from a folder and download it in laravel 9 application.

Here i will show, how to create zip file and download in laravel 9, ziparchive laravel 9, create zip file in laravel 9, create a zip file from a folder and download in laravel 9, create zip file using ziparchive in laravel 9.

Read Also :  Laravel Blade For Loop Example

Example : Laravel 9 Create Zip File and Download

Step 1: Create Route

In this step we will create route for create zip  and download in laravel application.

<?php
  
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ZipArchiveController;
 

Route::get('download-zip', [ZipArchiveController::class, 'downloadZip']);

Step 2: Create Controller

Now, in this step we will create ZipArchiveController. In this controller we will write code for create zip file.app/Http/Controllers/ZipArchiveController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use ZipArchive;

class ZipArchiveController extends Controller
{
    public function downloadZip()
    {                                
        $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));
    }
}

In the last i have created a Zip_Example folder in the public folder and added some images. So, you required to also create one folder and add some files also.

Read Also :  Laravel 9 Socialite Login with Google Example

After you enter the following url in the browser and see the output.

http://localhost:8000/download-zip

I hope you understand of Laravel 9 create zip file and it can help you…