It is preferable to make one archive and allow users to download it if you require them to be able to download many files at once. The laravel method is shown here.
Actually, we will be utilizing the ZipArchive class, which has been there since PHP 5.2, It's less about Laravel and more about PHP. To utilize it, confirm that the ext-zip extension is enabled in your php.ini.
How to Create Zip File and Download in Laravel
Here's the code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ZipController extends Controller
{
public function downloadZip(Request $request){
$zip_file = 'invoices.zip';
// Initializing PHP class
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$invoice_file = 'invoices/AMZ-001.pdf';
// Adding file: second parameter is what will the path inside of the archive
// So it will create another folder called "storage/" inside ZIP, and put the file there.
$zip->addFile(storage_path($invoice_file), $invoice_file);
$zip->close();
// We return the file immediately after download
return response()->download($zip_file);
}
}
That's it.
Thank you for reading this article.