DEV Community

𝒮𝒶𝓇𝓉𝒽𝒶𝓀 📨
𝒮𝒶𝓇𝓉𝒽𝒶𝓀 📨

Posted on

File Upload in Livewire v 1.2.0

File handling is very hard to handle, specially if you are using javascript to send file and then handling on laravel/php side.

With new Laravel Livewire v1.2.0, there is a new way to upload file with zero configuration (Yes no config needed)

Check this video for extensive explaination of every bit of new file upload.

Before moving forward, I can tell you that this is soo easy that you may thing there is some magic behind it, but not its super simple.

Note: If you are new to laravel livewire, check this full livewire course link at the bottom of this post.

First, add the WithFileUploads trait to your component.

use Livewire\Component;
use Livewire\WithFileUploads;

class UploadPhoto extends Component
{
    use WithFileUploads;

    public $photo;

    public function save()
    {
        $this->validate([
            'photo' => 'image|max:1024', // 1MB Max
        ]);

        $this->photo->store('photos');
    }
}
Enter fullscreen mode Exit fullscreen mode

then just use wire:click on your input field to handle any file upload.

<form wire:submit.prevent="save">
    <input type="file" wire:model="photo">

    @error('photo') <span class="error">{{ $message }}</span> @enderror

    <button type="submit">Save Photo</button>
</form>
Enter fullscreen mode Exit fullscreen mode

That's it.
I told you, it is super simple.

Livewire full video course

For more information and awesome tutorials, follow me at https://twitter.com/sarthaksavvy

watch tutorials on https://youtube.com/bitfumes

Top comments (1)

Collapse
 
neeraj1005 profile image
Neeraj Singh

Sir can you tell me how can I perform autoload image without form or submit button? How can I perform onload event in livewire...?