Laravel 11 Create Zip Archive File Tutorial

Compressing files is a frequent requirement in web development, and Laravel, a well-known PHP framework, provides multiple approaches to generate zip files. Whether you choose to use Laravel’s built-in capabilities or take advantage of Laravel packages, this guide will walk you through both methods. So using this Laravel Create Zip Archive File Tutorial we will learn how to generate how to Create ZIP Archive with Files And Download it in Laravel.

1. Using Built-in Method

First, add routes to the routes/web.php file to handle zip archive creation and download requests:

<?php

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

Route::get('zip-file-download', ZipController::class);

Generate a controller with the following command:

php artisan make:controller ZipController

Next, edit the app/Http/Controllers/ZipController.php file to include a method that generates a zip file and returns it as a download response:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use File;
use ZipArchive;

class ZipController extends Controller
{
/**
* Handle the zip file creation and download.
*
* @return \Illuminate\Http\Response
*/
public function __invoke()
{
$zip = new ZipArchive;
$fileName = 'myNewFile.zip';

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

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

$zip->close();
}

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

Start the application server with:

php artisan serve

Then, open your browser and navigate to http://localhost:8000/zip-file-download.

2. Using External Package

For this approach, you’ll need to install the stechstudio/laravel-zipstream package using composer:

composer require stechstudio/laravel-zipstream

Create a route to manage zip file creation requests:

<?php

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

Route::get('file-download-zip', ZipController::class);

Update the method in the controller to generate a zip file and return it as a response:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use File;
use Zip;

class ZipController extends Controller
{
/**
* Handle zip file creation and download.
*
* @return \Illuminate\Http\Response
*/
public function __invoke()
{
return Zip::create('zipFileName.zip', File::files(public_path('myFiles')));
}
}

Run the server with:

php artisan serve

And then visit http://localhost:8000/file-download-zip in your browser.