how to make a zip file from a folder and download it in Laravel step by step. In this php laravel application, we will produce a zip file by utilizing the zip-archive class.
Letsdemonstrate how to implement a very simple zip file method in a Laravel application. So let’s seea few items stepsand consider them as an example. I will show you two method.
Fist Method which is using ZipArchive Class
- Setup Laravel
Route::get('download-zip-file', [ZipDownloadController::class, 'downloadZipFile']);
- The same as with route above, we will add one new route method here. downloadZipFile() will build a new zip file and download it as a response, so Please add this line.
<strong><?php</strong>
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
use ZipArchive;
class ZipDownloadController extends Controller
{
<em>/**
</em><em> * Display a listing of the resource.
</em><em> *
</em><em> * @return \Illuminate\Http\Response
</em><em> */</em>
public function downloadZipFile()
{
$zip = new ZipArchive;
$fileName = 'myFolder.zip';
if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
{
$files = File::files(public_path('myFolder'));
foreach ($files as $key => $value) {
$relativeNameInZipFile = basename($value);
$zip->addFile($value, $relativeNameInZipFile);
}
$zip->close();
}
return response()->download(public_path($fileName));
}
}
NOTE: Make sure you have myFolder in your public path/directory.
- Now run your project with this command
php artisan serve
to start developement server. - Now please go the route like
http://127.0.0.1:8000/download-zip-file
from your browser, it will make the folder zip and download automatically.
Second Method : Using open-source Laravel Zip Package
- We are keeping same route to make it quick
Route::get('download-zip-file', [ZipDownloadController::class, 'downloadZipFile']);
- Go to controoller and just follow this
downloadZipFile
method.
<strong><?php</strong>
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
use ZipArchive;
class ZipDownloadController extends Controller
{
<em>/**
</em><em> * Display a listing of the resource.
</em><em> *
</em><em> * @return \Illuminate\Http\Response
</em><em> */</em>
public function downloadZipFile()
{
<em>//only add this code.</em>
return Zip::create('myFolder.zip', File::files(public_path('myFolder')));
}
}
NOTE: Make sure you have myFolder in your public path/directory.
- Now run your project with this command
php artisan serve
to start developement server again.Go the route, thats will create zip folder at your public path.
From avobe two method i personally prefer 2nd one. Cause thats easy to handle and quick. hope both method is working, if not please feel free to comment.