Laravel Livewire Drag-n-Drop Files Upload Using AlpineJS

Faizan Aalam
2 min readJun 29, 2021

--

Image by cocoparisienne from Pixabay

As the name suggests it's a step-by-step tutorial for drag-n-drop files upload using alpine.js in Laravel Livewire, I am assuming that you already created your project, this tutorial is just a snippet and idea to include drag-n-drop file upload feature so without wasting time on what is Laravel Livewire, AlpineJS and project setup lets get straight to our topic.

Step #1 LiveWire Component

We’ll create a livewire component for our file upload so that we can use it in our project.

Run this command in terminal/cmd

php artisan make:livewire FilesUpload

It will create two files one in app/Http/Livewire/FilesUpload.php and the other one in resources/views/livewire/files-upload.blade.php

Now you can use this component anywhere in your Laravel project as

<livewire:files-upload />

Or alternatively

@livewire('files-upload')

Step #2 Changing Blade Template

Open resources/views/livewire/files-upload.blade.php and replace with the following code.

Here we are creating an AlpineJs component for handling the file drop. The drop , dragover and dragleave are the javascript events. Livewire exposes dedicated JavaScript functions for integration with 3rd-party file-uploading libraries you can learn more here, the functions exist on the JavaScript component object, which can be accessed using the convenience Blade directive: @this you can read more about it @this here.

Step #3 Handling The Uploaded File

Open app/Http/Livewire/FilesUpload.php and replace it with the following code.

Most of the code here is self-explanatory, I am using the LiveWire WithFileUploads you can read more here, the updatedFiles() function trigger every time whenever the files dropped in the frontend, also you can handle the files in updatedFiles() function using the Laravel Storage or Livewire file upload, read more here.

Conclusion

This is a small tutorial on how to make a drag-n-drop file upload livewire component to use in the Laravel project.

--

--