In this post, I will show you how to create and download a zip file in Laravel 9. Laravel has a ZipArchive class for creating zip files.
Create and download a ZIP file containing your Laravel 9 application. It assumes you already have Laravel installed so you can start coding right away.
Step 1. Create Route
Step 2. Create Controller
Step 3. Call the Route to URL
Step 4. Conclusion
Step 1. Create Route
Open web.php file then write a new route.
Route::get('download', [ZipDownloadController::class, 'downloadZip']);
Step 2. Create Controller
In this step create a new controller with name ZipDownloadController , You can choose your desire name also, I am choose this because already i used the name is route. If you change the name kindly change in web.php file also.
In this controller i will use images directory and putted some excel or any files. Put images inside public directory, Like below path.
YourProject/public/images
app/Http/Controllers/ZipDownloadController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use ZipArchive; class ZipDownloadController extends Controller { public function downloadZip() { $zip = new ZipArchive; $fileName = 'Images.zip'; if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE) { $files = \File::files(public_path('images')); foreach ($files as $key => $value) { $file = basename($value); $zip->addFile($value, $file); } $zip->close(); } return response()->download(public_path($fileName)); } } ?>
Step 3. Call the Route to URL
In this step you will get your result. So Just call your newly created route to your browser.
http://localhost:8000/download
Step 4. Conclusion
In this post i will show you how you can create a zip and make it downloadable, This will help you when every you will make an app which will allow to download some files. Also this will help to download some excel or PDF file like studies material.
Hope you like this, Thanks