Throughout this Laravel Create Zip File example tutorial you will learn how to generate zip files and download them in the Laravel 10 application.
To generate zip file in laravel we just need to use the ZipArchive package. This package gives us a easy and simple way to create zip archive in laravel application.
#1 Download Laravel App
First, you just need to download or install a fresh Laravel application using the following command.
composer create-project --prefer-dist laravel/laravel laravel-create-zip
Next, go into your installed app directory:
cd laravel-create-zip
#2 Create Routes for Zip File in Laravel
Now open your routes/web.php file and put the resource routes on it. This resource route handles your all Laravel ajax crud operation.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ZipController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('export-zip', [ZipController::class, 'exportZip']);
Route::get('/', function () {
return view('welcome');
});
#3 Create Controller
Now create a new controller as ProductController just running the below command.
php artisan make:controller ZipController
After successfully creating the controller, now open the app/Http/Controllers/ZipController.php file and put the methods on it.
<?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 exportZip()
{
$zip = new ZipArchive;
$fileName = 'zipfile.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));
}
}
#4 Start your app
In the last step, open the command prompt and run the following command to start the development server:
php artisan serve
Then open your browser and hit the following URL on it:
https://localhost:8000/export-zip