To create and download a zip file in Laravel, use the “ZipArchive” class.
Here is the step-by-step guide:
Step 1: Install Laravel
composer create-project laravel/laravel zip-app
Step 2: Create a controller file
php artisan make:controller ZipperController
Add the folder inside public >> images and add images
Add the below code inside the ZipperController.php file.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use File; use ZipArchive; class ZipperController extends Controller { public function __invoke() { $zip = new ZipArchive; $fileName = 'data.zip'; if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE) { $files = File::files(public_path('images')); foreach ($files as $key => $value) { $relativeNameInZipFile = basename($value); $zip->addFile($value, $relativeNameInZipFile); } $zip->close(); } return response()->download(public_path($fileName)); } }
Step 3: Create a Route inside the web.php file
Add the below code inside the routes >> web.php file.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\ZipperController; Route::get('/', function () { return view('welcome'); }); Route::get('download-zip-file', ZipperController::class);
Step 4: Run the project
Go to the project’s root and start the Laravel server using this command:
php artisan serve
Now, go to this command: http://localhost:8000/download-zip-file
You will see that it will download the data.zip file.
That’s it!
akshay
I have used chumper/zipper package the code works fine but when i download the zipped archive i am getting no archive found. is there any solution to this or any other package. Suggestions would be helpful,thank you.
Size of zipped files: https://pasteboard.co/Hpz00p7.png
afterdownloading: https://pasteboard.co/HpyYDQ3.png
Mike
I enjoy the article