How to Create Zip File and Download in Laravel 7/8?

in this tutorial, i am writing how to create zip file and download in laravel with archive file and downloading with few steps follow and you any one file to zip converter in php

Step 1: Create Route How to Create Zip File and Download in Laravel 7/8?

in this step 1 to follow only below and add router your code below. happy

routes/web.php

Route::get('download_zip', 'ZipController@downloadZipFile');

Step 2: Create Controller

in this step to create controller and get this router call and get this file zip convert is soon.

<?php
   
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use File;
use ZipArchive;
  
class ZipController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function downloadZipFile()
    {
        $zip = new ZipArchive;
   
        $fileName = 'NewFile.zip';
   
        if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
        {
            $files = File::files(public_path('myFiles'));
   
            foreach ($files as $key => $val) {
                $ZipFile = basename($val);
                $zip->addFile($val, $ZipFile ;
            }
             
            $zip->close();
        }
    
        return response()->download(public_path($fileName));
    }
}

Ok now i hope this code follow to you :: How to Create Zip File and Download in Laravel 7/8.

Now run this command below seee and run your code in localhost or live.

php artisan serve

Last command after run and get this url run your browser:

http://localhost:8000/download_zip

Do you want to hire us for your Project Work? Contact us

2 thoughts on “<strong>How to Create Zip File and Download in Laravel 7/8?</strong>”

Leave a Comment