Skip to main content
in Laravel

Zip-archive on the fly in Laravel

There are situations where you want to serve the user multiple files. In this example, we will create a simple zip archive with the help of laravel.

First, we create our form for handling the file uploads.

<form method="post" action="{{ route('compress') }}" enctype="multipart/form-data">
    @csrf
    <label for="files">Submit your files</label>
    <input name="files[]" id="files" type="file" multiple />

    <button>Compress files</button>
</form>

Then we have to handle the request and archive those uploaded files into a zip-archive.

Laravel makes it easy for us to remove the file after sending it to our users with the deleteAfterSend() method.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use ZipArchive;

class CompressFileController 
{
    public function __invoke(Request $request)
    {
        $zip = new ZipArchive();
        $zip->open($path = storage_path('app/tmp'.Str::random()), ZipArchive::CREATE);

        foreach ($request->file('files') as $file) {
            $zip->addFromString(
                $file->getClientOriginalName(),
                $file->getContent()
            );
        }

        $zip->close();

        return response()->download($path, 'archive.zip')->deleteFileAfterSend();
    }
}