Laravel 11 - How to Create ZIP Archives

Touseef Afridi
31 Oct 24

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!


Quick Overview

This guide walks you through setting up a Laravel project and using the laravel-zipstream package to create a ZIP file of images. It starts with creating a fresh Laravel project and selecting basic configuration options. You'll then install the laravel-zipstream package, which automatically registers the service provider and facade. Next, you'll create a ZipController to handle the logic of retrieving images from a specified directory and generating a downloadable ZIP file. A route is defined to trigger the downloadZip() function. After preparing an images folder in the public directory and adding some image files, you'll test the functionality by starting the Laravel development server and accessing the route to download the ZIP file.

Step # 1 : Create fresh Laravel project or use existing project.

If Laravel is installed globally on your machine, you can easily create a new Laravel project by running the following command in your terminal.
laravel new zip
Or
If Laravel is not installed globally, don't worry! You can still create a new project using Composer by running the following command.
composer create-project laravel/laravel --prefer-dist zip
After executing one of the above commands, you will be prompted.
  1. Would you like to install the starter kit? — Choose none
  2. After selecting None, you'll be asked about testing framework. — Choose Pest
  3. After selecting Pest, you'll be asked to select the database for your application. — Choose mysql
  4. After selecting MySql, you'll be asked if you want to run the default database migration. — Type yes

Once the migration is complete, your Laravel project will be set up and ready for development.

Step # 2 : Access the project.

After successfully setting up the project, the next step is to access your project’s root folder. Open a terminal (e.g., Git Bash, Command Prompt, or Terminal) and navigate to the directory where the Laravel project was created.
cd c:xampp/htdocs/zip
This will ensure that you are in the correct project directory and ready to start installing packages and setting up the controller.

Step # 3 : Install the Zipstream package.

Now that your Laravel project is set up, it's time to install the laravel-zipstream package, which will allow you to easily create ZIP files in your Laravel application. To install the package, run the following command.
composer require stechstudio/laravel-zipstream
Once you run this command, Composer will fetch and install the package along with its dependencies. The best part is that the service provider and facade will be registered automatically, so you don't need to manually configure them. This is a great feature, as it saves you from writing additional code to register the service provider.

Step # 4 : Publish the configuration (Optional)

While the laravel-zipstream package works out of the box with default settings, you might want to customize some of the package’s configuration options. For example, you might want to adjust the buffer size, specify default filenames, or tweak other settings to suit your needs. If you want to make any adjustments, you'll need to publish the configuration file. To publish the configuration, run the following command
php artisan vendor:publish --provider="STS\ZipStream\ZipStreamServiceProvider"
This will generate a zipstream.php file in the config directory of your Laravel project. Open this file, and you'll see a variety of configurable options like buffer size and default file settings. Feel free to make adjustments according to your preferences.

Step # 5 : Create a ZipController.

With the laravel-zipstream package installed and the configuration set up, the next step is to create a controller that will handle the logic for zipping files. This is where the ZipController will come into play. Run the following command to generate the ZipController.
php artisan make:controller ZipController
Next, open the ZipController.php file located in the app/Http/Controllers directory. Update the file 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);
    }
}
The downloadZip function defines the path to the images folder within the public directory of the Laravel project. It then retrieves all the files within the images folder and stores their full paths in an array. Once all the files are collected, the function uses the Zip::create method from the laravel-zipstream package to generate a ZIP file that contains the selected images. Finally, the function sends the ZIP file to the user, allowing them to download it directly. This process ensures that images are dynamically compressed into a ZIP archive for easy access and download.

Step # 6 : Create a Route.

With the controller in place, the next step is to create a route that will invoke the downloadZip function. To do this, open the routes/web.php file, import the ZipController, and define the route.
use App\Http\Controllers\ZipController;
Route::get('/zip', [ZipController::class, 'downloadZip']);
This route will map the /zip URL to the downloadZip() function in the ZipController. When the user accesses the /zip route, the function will be triggered, generating and downloading the ZIP file.

Step # 7 : Prepare the Images Directory.

Navigate to the public directory of your Laravel project, create a new folder named images, and add several image files (e.g., .jpg, .png) into it. This will ensure there are files available for zipping when testing the downloadZip() function.


Step # 8 : It's time to test.

Start the Laravel development server by running.
php artisan serve
To download the ZIP file, access the following URL in your browser.
127.0.0.1:8000/zip

Once downloaded, extract the ZIP file, and you will see the images or files that were included.

Conclusion

By following this guide, you've successfully integrated the laravel-zipstream package into your Laravel project, enabling the creation and downloading of ZIP files containing images. You've set up a controller and route to dynamically generate the ZIP archive, and you've ensured that the functionality works by testing it with your own image files. This solution offers a simple way to serve compressed files to users, and you can further customize the process by adjusting the package's configuration settings.
For more details, check the laravel-zipstream documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering