In Laravel 11, Zip file is a compressed archive format, there are two simple ways to create and download it, the first way is build in method, and the second way is external package like stechstudio/laravel-zipstream
.
Let’s start to create and download a zip archive file using in built method and external package:
#1 Using Built-in Method
Create routes in resource/web.php
file to create a zip archive and download requests in it:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ZipController;
Route::get('zip-file-download', ZipController::class);
Run the following command to create a controller file:
php artisan make:controller ZipController
Edit app/Http/Controllers/ZipController.php
file, and create method in it to generate new zip file and download as response:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
use ZipArchive;
class ZipController extends Controller
{
/**
* Display a listing of the resource.
*
* @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 $key => $value) {
$relativeNameInZipFile = basename($value);
$zip->addFile($value, $relativeNameInZipFile);
}
$zip->close();
}
return response()->download(public_path($fileName));
}
}
Run the following command to start application server:
php artisan serve
Open browser and type http://localhost:8000/zip-file-download
.
#2 Using External Package
In this way, you need to install stechstudio/laravel-zipstream
by running the composer command:
composer require stechstudio/laravel-zipstream
Create a route to handle create a zip archive file requests:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ZipController;
Route::get('file-download-zip', ZipController::class);
Make method in controller file to generate new zip file and download as response:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
use Zip;
class ZipController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __invoke()
{
return Zip::create('zipFileName.zip', File::files(public_path('myFiles')));
}
}
un the following command to start application server:
php artisan serve
Open browser and type http://localhost:8000/file-download-zip
.