@ryleigh
To enable users to download a zip file through the browser in Laravel, you can follow these steps:
- Create a route in your web.php file that points to a controller method:
1
|
Route::get('/download-zip', 'ZipDownloadController@downloadZip');
|
- Create a controller named ZipDownloadController using the Artisan command:
1
|
php artisan make:controller ZipDownloadController
|
- In the ZipDownloadController, create a method called downloadZip that will generate and download the zip file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use ZipArchive;
use File;
class ZipDownloadController extends Controller
{
public function downloadZip()
{
$zip = new ZipArchive;
$fileName = 'example.zip';
if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE) {
// Add files to the zip file
$zip->addFile(public_path('file1.txt'), 'file1.txt');
$zip->addFile(public_path('file2.txt'), 'file2.txt');
$zip->close();
}
return response()->download(public_path($fileName));
}
}
|
- Make sure to have the files that need to be zipped in your public directory. In this example, file1.txt and file2.txt should be placed inside the public directory.
- Finally, create a link in your blade file that points to the URL of the route you created:
1
|
<a href="{{ url('/download-zip') }}">Download ZIP file</a>
|
When a user clicks on the "Download ZIP file" link, it will trigger the downloadZip
method in the ZipDownloadController
, which will generate and download the zip file containing the specified files.