Laravel 11 - How to Create ZIP Archives
Laravel 11 - How to Create ZIP Archives
In this tutorial, we will discuss how to create ZIP files in Laravel 11. This functionality simplifies file organization and enhances data handling.
If you're a video person, feel free to skip the post and check out the video instead!
Step # 1 : Create fresh Laravel project or use existing project.
Two commands to create fresh laravel project
Global Command : laravel new zip
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist zip
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/zip
Step # 3 : Install the package.
Command : composer require stechstudio/laravel-zipstream
The service provider and facade will be automatically wired up.
Step # 4 : Publish the configuration.
This step is optional. If you want to customize the package's default configuration, publish the config file using.
Command : php artisan vendor:publish --provider="STS\ZipStream\ZipStreamServiceProvider"
This will create a zipstream.php file in the config directory, where you can adjust options like buffer size, default filenames, and more.
Step # 5 : Create a controller.
Run the following command to create the ZipController.
Command : php artisan make:controller ZipController
Then, update the ZipController with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use STS\ZipStream\Facades\Zip;
class ZipController extends Controller
{
public function downloadZip()
{
// Define the path to the 'images' folder in the public directory
$imagesPath = public_path('images');
// Get all files in the 'images' folder
$files = [];
foreach (File::files($imagesPath) as $file) {
// Add the full path of each file to the array
$files[] = $file->getPathname();
}
// Create the ZIP and pass the array of file paths
return Zip::create('images.zip', $files);
}
}
Step # 6 : Create a route.
Import ZipController class, create a route.
use App\Http\Controllers\ZipController;
Route::get('/zip', [ZipController::class, 'downloadZip']);
Step # 7 : Prepare the Images Directory
To test the ZIP functionality, create an images folder within the public directory of your Laravel project. Inside this folder, add several image files (e.g., .jpg, .png) to ensure there are files available for zipping.
Step # 8 : It's time to test.
Start the Laravel development server.
Command : php artisan serve.
To download the ZIP file .Access below URL.
127.0.0.1:8000/zip
Once downloaded, extract the ZIP file, and you will see the images or files that were included.
For more details please refer to the package documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments