Laravel 10 - Zip Files (Zip & Unzip files)

Touseef Afridi
09 Sep 24

Laravel 10 - Zip Files (Zip & Unzip files)

In this tutorial, we will discuss how to download, zip, and unzip files. This is useful for managing file storage and transfer efficiently.


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
Next, install the required dependencies and run the Laravel Vite development server for front-end assets:
Command : npm install && npm run dev
In a new terminal window or tab (while keeping the Vite server running), navigate to the same project directory to execute further Laravel command.

Step # 3 : Install the package.

Command : composer require zanysoft/laravel-zip

Step # 4 : Create a controller.

Command : php artisan make:controller ZipController
Access ZipController and update it as following.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Zip;
class ZipController extends Controller
{
 public function index()
 {
  // Note : Create a folder named images inside public folder. For testing purpose put some images inside images folder.
  //Lets create a Zip file of the images folder that exist in the public directory.
  //Zip file will be saved in public directory and downloaded with the name Nature_images.zip
  $zip = Zip::create('Nature_images.zip');
  $zip->add(public_path('/images'));
  $zip->close();
  return response()->download(public_path('Nature_images.zip'));
 }
}

Step # 5 : Let's update the welcome route.

Route::get('/', [App\Http\Controllers\ZipController::class, 'index']);

Step # 6 : It's time to test.

Start the Laravel development server.
Command : php artisan serve.
Access below URL
127.0.0.1:8000
Zip file will be saved in public directory and downloaded with the name Nature_images.zip
You can also extract the images update the index method as following.
 public function index()
 {
     //Let's extract the nature_images.zip that we just created in the public folder. It will be named as extractedFiles.
  $zip = Zip::open('Nature_images.zip');
  $zip->extract(public_path() . '/extractedFiles');
  dd("done");
 }

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