Dwight Watson's blog

Uploading files with Laravel Livewire and Laravel Vapor

This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.

I've just recently started working with Laravel Livewire, now that it ships as an option with the new Laravel Jetstream. Livewire is a really interesting approach to avoid writing client-side JavaScript by dynamically re-rendering your views on the server-side. It also supports file uploads, by doing some neat trickery behind the scenes - creating a pre-signed upload URL to S3 and uploading directly to your bucket.

On this project I'm working with, I also happen to be going serverless with Laravel Vapor. What's interesting about Vapor is that it also supports file uploads this way. Rather than proxying a file upload through a Lambda function (where you're charged by the time it's running), Vapor creates a pre-signed upload URL to S3.

What's interesting about this is both Livewire and Vapor approach uploads the same way. Pre-sign a URL to upload to a temporary directory, persist the file by moving it out of the temporary directory, and have a command that runs daily to remove outdated files from the temporary directory (i.e. files that for whatever reason did not get persisted). For this to work with Livewire, it wants you run a daily command - php artisan livewire:configure-s3-upload-cleanup. However - Laravel Vapor is going to do something similar out of the box for you.

So, rather than stuff around with trying to configure Livewire's upload system on Vapor, I figured it would be better to make Livewire act like Vapor's upload system. That is - instead of uploading to a Livewire specific directory, use Vapor's upload directory and let Vapor take care of the automatic file removal. Luckily - this is a pretty easy configuration once you've published your Livewire config.

'temporary_file_upload' => [
//
'directory' => 'tmp', // Use Vapor's 'tmp' default instead of the Livewire's 'livewire-tmp' default,
//
],

The only important option here is livewire.temporary_file_upload.directory. By setting it to tmp instead of the default livewire-tmp, your Livewire uploads will go to the same directory Vapor would have used had you uploaded from the client-side using Vapor.store. It also means you don't need to configure Livewire's manual cleanup process because Vapor will handle it for you out of the box.

A blog about Laravel & Rails by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.