25-Apr-2023
.
Admin
Hi friends,
Today, I explain how to create a zip file and download it in laravel 10. In this tutorial, I am writing an example of laravel 10 creating a zip archive file and downloading it in response. we will create a zip file using the zip-archive class in php laravel 10 application. I will give you an example step on step how to create a zip file from a folder and download it in laravel 10 application. I will give you examples step by step of how to create a zip file from a folder and download it in laravel 10 application. we will create a zip file using the zip archive class in php laravel 10 application.
In this post, I will show you how to create a very simple way to zip files in laravel 10 application. So let's follow a few things and make it a simple example.
Step 1: Download Laravel
Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip the following step.
composer create-project laravel/laravel example-app
Step 2: Add Route
First thing is we put one route in one for downloading the created zip file. So simply add both routes in your route file.
routes/web.php
<?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 within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('download-zip', [ZipController::class, 'downloadZip']);
Step 3: Add Controller
php artisan make:controller ZipController
Same things as above for the route, here we will add one new method for the route. downloadZip() will generate a new zip file and download as a response, so let's add below:
app/Http/Controllers/ZipController.php
<?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 downloadZip()
{
$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 Laravel App:
All steps have been done, now you have to type the given command and hit enter to run the Laravel app:
php artisan serve
Now, you have to open the web browser, type the given URL and view the app output:
http://localhost:8000/download-zip
I hope it can help you...
#Laravel 10