Create zip file and download in Laravel

This is a blog post explaining to create zip file and download in Laravel. we also see create zip single file or multiple files of a folder.

Some developer needs a file or a folder to zip and download at realtime when some website provides a downloadable link to the user. so this blog post explains how to archive or create zip file and download in Laravel.

Step:1 Install a Package name Zipper 

The first step we install a package Chumper/Zipper via composer, you can install using this command.

composer require chumper/zipper

After install add some code into Config/App.php

App.php

In Providers

 'providers' => [
                 'Chumper\Zipper\ZipperServiceProvider'
  ],

In aliases

 'aliases' => [
                'Zipper' => 'Chumper\Zipper\Zipper'
             ],

Step: 3 Create a route 

create a simple route to execute a method.

Route::get('download','ZipController@download');

Step: 4 Create a controller and use this package.

we install the package in our Laravel Application now, we can use it in the controller. we create a new controller for test purpose named ZipController

php artisan make: controller ZipController

And add function to download.

public function download()
    {
        $files = glob(public_path('folder/file.txt'));
        \Zipper::make(public_path("test.zip"))->add($files)->close();
        return response()->download(public_path("test.zip"));
    }

Zip a all file of a folder.

To zip and download all file of a folder using this code.

public function download()
    {
        $files = glob(public_path('folder/*'));
        \Zipper::make(public_path("test.zip"))->add($files)->close();
        return response()->download(public_path("test.zip"));
    }

Here we use only a * for all file of a folder.

So dear here we completed tutorials on how to create zip file and download in Laravel hope it helps you.