Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

technosml's avatar

Livewire 2 image upload not working

Here is my cod for updating avatar of user using livewire:

blade file:

    <div class="profile-pic-container">
        <img src="{{ asset($avatar) }}" alt="Profile Picture" id="profilePicture">
        <label for="fileInput"><i class="fas fa-edit edit-icon"
                onchange="document.getElementById('file').click();"></i></label>

        <div class="profile-userbuttons">
            <div class="upload-btn-wrapper">
                <form wire:submit.prevent="update_avatar">
                    @csrf
                    <input type="file" wired:model="avatar" name="avatar" id="fileInput" class="inputfile" onchange="document.getElementById('upload').click();"/>
                    <button class="btn" type="submit" name="upload" id="upload" style="display: none;">Change
                        Profile Picture</button>
                    @if($errors->has('avatar')) <span class="text-danger">{{ $errors->first('avatar') }}</span> @enderror
                </form>
            </div>
        </div>
    </div>

Livewire Class:

use WithFileUploads;

public $avatar;

public function mount($user)
{
    $this->avatar = $user->avatar;
}

// Validation rules
protected $rules = [
    'avatar' => 'image:jpeg,png,jpg|max:2048',
];

public function render()
{
    $user = Auth::user();
    return view('livewire.user-profile', compact('user'));
}

public function update_avatar()
{
    $validatedData = $this->validate([
        'avatar' => 'image:jpeg,png,jpg|max:2048',
    ]);
  														
        $extension = $this->avatar->extension();
        $user = Auth::user();
        
        $filename = $user->id.'_'.time() .'.'. $extension;
        
        $photo = Image::make($this->avatar)->resize(300, 300)->save(public_path('images/avatar/'.$filename));
        $photo->save();
        $old_avatar = $user->avatar;
        $user->avatar = 'images/avatar/'.$filename;

        if($user->save()){
            session()->flash('message.level', 'success');
            session()->flash('message.content', 'Profile photo updated successfully!');
        } else {
            session()->flash('message.level', 'error');
            session()->flash('message.content', 'Something went wrong.');
        }
}

In this code it always shows error "The avatar must be an image." while I am trying to upload an image and if I am dumping the $this->avatar variable inside update_avatar() it is giving me only string of file path which is stored in database in user's table. And uploading of file is not working.

It's on Livewire 2.

Is there anything wrong with this code?

0 likes
0 replies

Please or to participate in this conversation.