How to zip files in Laravel?

by edmond_brakus , in category: PHP Frameworks , 9 months ago

How to zip files in Laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 months ago

@edmond_brakus 

To zip files in Laravel, you can use the Zip facade.


Here's an example of how to zip a file:

1
2
3
4
5
6
use IlluminateSupportFacadesZip;

$zipFileName = 'my_zip_file.zip';

Zip::add('path/to/my_file.txt');
Zip::store($zipFileName);


You can also add multiple files to the zip file by using the add method multiple times:

1
2
3
Zip::add('path/to/my_file_1.txt');
Zip::add('path/to/my_file_2.txt');
Zip::store($zipFileName);


If you want to add the contents of an entire directory to the zip file, you can use the addDir method:

1
2
Zip::addDir('path/to/directory');
Zip::store($zipFileName);


You can also specify a base directory for the files in the zip file by passing a second argument to the add and addDir methods:

1
2
3
Zip::add('path/to/my_file.txt', 'files');
Zip::addDir('path/to/directory', 'files/directory');
Zip::store($zipFileName);


This will create a zip file with the structure files/my_file.txt and files/directory/.


Finally, you can download the zip file directly to the user's browser by using the download method:

1
return Zip::download($zipFileName);


I hope this helps! Let me know if you have any questions.