Create Zip Files and Enable Download Functionality in Laravel 9

Posted by

File compression and archiving are common tasks in web development, often required to bundle multiple files into a single, downloadable archive. In Laravel 9, a powerful PHP framework, achieving this functionality is straightforward using the ZipArchive class.

The code snippet you’ve provided is an example of how to create a zip file containing multiple files and offer it for download. Let’s dissect the code step by step.

public function __invoke()
{
    $zip = new ZipArchive;

    $fileName = 'myNewFile.zip';
 
    if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
    {
        $files = File::files(public_path('myFiles'));
 
        foreach ($files as $key => $value) {
            $relativeNameInZipFile = basename($value);
            $zip->addFile($value, $relativeNameInZipFile);
        }
           
        $zip->close();
    }
  
    return response()->download(public_path($fileName));
}

Here’s what each part of the code does:

$zip = new ZipArchive;: This line initializes a new ZipArchive object, which provides the functionality to work with zip archives.

$fileName = 'myNewFile.zip';: Here, you define the name of the zip file you want to create. You can customize this to suit your needs.

Opening the Zip Archive: The if condition checks if the zip archive can be opened for writing. If successful, it proceeds to add files to the archive.

Adding Files to the Zip Archive: Inside the loop, the code iterates through the files in the myFiles directory and adds each file to the zip archive. It uses addFile to specify the source file and the relative path within the archive.

Closing the Zip Archive: After adding all the files, the zip archive is closed using the close method.

return response()->download(public_path($fileName));: Finally, the code returns a response to download the created zip file. The public_path() function is used to specify the file path.

Usage Example

To use this code, you can create a route or controller method that invokes the code when a specific URL is accessed. For instance, if you want users to download a zip file by visiting example.com/download-zip, you can set up a route and controller for that URL.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x