Upload photo in Laravel Livewire

Upload and display photo using Laravel Livewire

Posted by Luke Beeno on November 17, 2022

Upload photo in Laravel Livewire

Upload and display photo using Laravel Livewire

Posted by Luke Beeno on November 17, 2022

Here is how you would upload a photo in Laravel Livewire:

If you want to copy the styling from the form, make sure you have boostrap.

Step 1. Declare photo variables in Livewire component

public $photo;
public $photo_name;

The above $photo variable will be used later to store photo value. Unless you have more information this variable as be named photo in order to work.

The $photo_name variable will be used to store the photo name.

Step 2. Create validation rule in Livewire component

protected function rules()
{
   return [
      'photo' => 'image|mimes:jpg,jpeg,png|max:1024'
   ];
}

Step 3. Create imgName method to get photo name

public function imgName($img){
   $this->photo_name = $img;
}

Step 4. Create save method to store photo

public function save(){
   $this->validate();
   $this->photo->storeAs('public/images', $this->photo_name);
}

The save method contains the validation method first, then the photo is stored.

The storeAs method contains two params, the first used to create directories that the photo will be stored.

The second parameter is used to name the photo. 

Step 6. Create form in Livewire blade

<div class="container">
    <form method="POST" wire:submit.prevent="save" enctype="multipart/form-data">
        <div class="row">
            <div class="col-6 mt-5">
                <div class="form-group mb-4">
                    <label for="photo">
                        Image <input aria-describedby="File" wire:model="photo" wire:change="storeImg($event.target.files[0].name)" type="file">
                    </label>
                </div>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </div>
    </form>
    <div class="col-6 pt-4">
        <img src="{{ asset('storage/images/example.png') }}" alt="photo"/>
    </div>
</div>

The form will let you select file and click save to store. The file will be stored in the storage/app directories.