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();
}
}
Related articles
Laravel query scopes
Laravel Eloquent Query Scopes can save time and eliminate inefficiencies when retrieving data from the database by allowing you to define reusable queries.
Read more
Saving a html canvas element to your server
Saving user-generated content from an HTML canvas element to a PHP backend can be a useful way to store and process canvas-based graphics and images.
Read more
Sending a test email from laravel artisan tinker
Debugging failing email can be a big pain. One of the steps is to send a test email from your production server. This snippet provides an easy way to do so.
Read more