How to Upload Images & Files Using LiveWire Example

Livewire puts web devs on ease by obliterating the complexiy that React and Vue bring to our projects. It’s a complete framework that simplifies our web apps in Laravel. Their added file upload functionality simplifies the taks which we can see on Github and it’s once again in a simplest way as compared to its contemporaries. Here we are using Livewire new method to upload images using it.
So if you are wondering which one to choose from React, Vue and Livewire you should see how simplified this job would have been in React and Vue. This tutorial is about using livewire to upload files or images to our remote server ‘rs1’.

Let’s assume we already have a LiveWire profile component that we use for updating the avatar of an online user

class Profile extends Component
{
  use WithFileUploads;
 
  public $avatar;
 
  public function save()
  {
    $this->validate(['avatar' => 'image']);
 
    $filename = $this->avatar->store('avatars', 'rs1'); // Using it to upload image to our remote server rs1
 
    auth()->user()->update([
        'avatar' => $filename
    ]);
  }
 
  public function render()
  {
    return view('livewire.profile');
  }
}

Now let’s move to our component’s view file and make changes in it.

<form wire:submit.prevent="save">
    <input wire:model="avatar" type="file" name="avatar">
 
    <button>Change</button>
</form>

That was all for it. We can use this method to upload files and keep our code clean without running into complexities. That new Liewire image upload support and functionality has literally simplified a hectic job.