Create Zip File and download in Laravel(without using any packages)

Sandeeppant
1 min readFeb 13, 2025

--

First of all we will create a controller :

php artisan make:controller InvoiceController

Now open InvoiceController and create a method downloadZip()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class InvoiceController extends Controller
{
public function downloadInvoicesZip(){

$directory = 'invoices';
$zipFileName = "Invoice-" . date("y-m-d-h-i-s") . ".zip";
$zipFilePath = storage_path("app/{$directory}/invoice.zip");
$sourcePath = storage_path('invoice');

// Ensure the directory exists
Storage::disk('local')->makeDirectory($directory, 0775);

// Create and open zip archive
$zip = new ZipArchive();
if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourcePath));

foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($sourcePath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
} else {
return response()->json(['error' => 'Failed to create ZIP archive'], 500);
}

return Response::download($zipFilePath, $zipFileName, ['Content-Type' => 'application/octet-stream']);
}
}

Here we are using ZipArchive() class , you can read more about this on this link

Now create a route, open web.php

//web.php
use App\Http\Controllers\InvoiceController;

Route::get('/invoice-download',[InvoiceController::class, 'downloadZip']);

And that’s it… 🤗

Thank you for reading. 🙋‍♂️

🏌️‍Follow me: https://medium.com/@sandeeppant

--

--

No responses yet