In this post we'll see how to create a zip file and download it in laravel.
Let's start
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 downloadZip()
{
Storage::disk('local')->makeDirectory('tobedownload',$mode=0775); // zip store here
$zip_file=storage_path('app/tobedownload/invoices.zip');
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$path = storage_path('invoices'); // path to your pdf files
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $name => $file)
{
// We're skipping all subfolders
if (!$file->isDir()) {
$filePath = $file->getRealPath();
// extracting filename with substr/strlen
$relativePath = substr($filePath, strlen($path) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
$headers = array('Content-Type'=>'application/octet-stream',);
$zip_new_name = "Invoice-".date("y-m-d-h-i-s").".zip";
return response()->download($zip_file,$zip_new_name,$headers);
}
}
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 all... 🤗
Top comments (1)
hi friend,
if I want download some file, then delete it, I can use command:
but open question is:
if I want download some file, then delete it and then redirect Laravel application to some other page/route?
What is code for this case? Can you help me pls ...