Saleem.dev
Published on

Upload images and files using Laravel Livewire

Authors

Consider we have a LiveWire profile component used to update the logged-in user avatar

<?php
 
namespace App\Livewire;
 
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Validate;
 
class UploadPhoto extends Component
{
    use WithFileUploads;

    #[Validate('image')]
    public $avatar;

    public function save()
    {
        $filename = $this->avatar->store(path: 'avatars', 's3'); // uploading the file to aws s3

        auth()->user()->update([
            'avatar' => $filename
        ]);
    }

    public function render()
    {
        return view('livewire.profile');
    }
}

Then, in component's view:

<form wire:submit="save">
    <input wire:model="avatar" type="file" name="avatar">

    <button type="submit">Change photo</button>
</form>

That's it, try it if you don't believe :)

To dive in more, head over to the official documentation.

Happy coding!