“The avatar must be an image” when trying to upload an image (.png)

I am trying to update a user’s avatar, however I keep getting the error “The Avatar must be an image”. But the update function on other part of the profile works like name email, etc..
I am really confuse on why it is not working? Any help would be highly appricated…
I am currently using livewire/livewire version 3.4, php version 8.2 and laravel/framework version 11.9, I have also did php artisan storage:link.
My code is bellow.

<?php

namespace AppLivewire;

use LivewireComponent;
use LivewireWithFileUploads;
use AppModelsUser;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesHash;

class Users extends Component
{
    use WithFileUploads;
    public $users, $name, $email,
    $role, $avatar, $user_id,
    $currentAvatar = null;
    public $isOpen = false;

    public function render()
    {
        $this->users = User::all();
        return view('livewire.user', ['users' => User::all()])
        ->extends('layouts.app')
        ->section('content');
    }


    public function create()
    {
        $this->resetInputFields();
        $this->isOpen = !$this->isOpen;
        session()->flash('message', 'Create method triggered');
    }

    public function openModal()
    {
        $this->isOpen = true;
    }

    public function closeModal()
    {
        $this->isOpen = false;
    }

    private function resetInputFields()
    {
        $this->user_id = null;
        $this->name = '';
        $this->email = '';
        $this->role = 'student';  // Default role
        $this->avatar = null;

    }

     public function store()
     {
         $this->validate([
             'name' => 'required|string|max:255',
             'email' => 'required|email|unique:users,email,' . $this->user_id, 
             'role' => 'required|in:admin,lecturer,student',
             'avatar' => 'nullable|image|mimes:jpeg,jpg,png,gif|max:1024',
         ]);

         $validatedData = [
            'name' => $this->name,
            'email' => $this->email,
            'role' => $this->role,
        ];

         // Handle avatar upload(store file and save path)
         if ($this->avatar) {
            // Get file extension
            $extension = $this->avatar->getClientOriginalExtension();

            // Generate unique filename
            $filename = 'avatar-' . time() . '.' . $extension;

            // Store file publicly with custom filename
            $validatedData['avatar'] = $this->avatar->storePubliclyAs(path: 'avatars', name: $filename, disk: 'public');
        }

        // Using updateOrCreate to insert or update the user
        User::updateOrCreate(
            ['id' => $this->user_id],
            array_merge($validatedData, [
                'password' => $this->user_id
                    ? User::find($this->user_id)->password
                    : Hash::make('password'), // Default password for new users
            ])
        );

         session()->flash('message', $this->user_id ? 'User Updated Successfully.' : 'User created successfully.');
         $this->closeModal();
         $this->resetInputFields();
     }

    public function edit($id)
    {

        $user = User::findOrFail($id);
        $this->user_id = $id;
        $this->name = $user->name;
        $this->email = $user->email;
        $this->role = $user->role;
        $this->currentAvatar = $user->avatar;

        $this->openModal();
        session()->flash('message', 'Edit method triggered');
    }
}

And part of the blade file, please note in my app.blade.php I have @livewireScripts in the body and @livewireStyle in head:

<div>
            <!-- Check if a new avatar file is uploaded and show its preview -->
            @if (!empty($currentAvatar))
                <img src="{{ Storage::url($currentAvatar) }}" class="mt-2" width="100" alt="Current Avatar" />

                <!-- If no avatar is uploaded or stored, show upload input and "No avatar uploaded" message -->
            @else
                <p>No avatar uploaded</p>
            @endif

            <!-- Input field for uploading an avatar -->
            <x-input-label for="avatar" :value="__('Avatar')" />
            <input wire:model.live="avatar" id="avatar" name="avatar" type="file" accept="image/*" class="mt-1 block w-full" />
            <x-input-error class="mt-2" :messages="$errors->get('avatar')" />
        </div>

Don’t know if this helps, my schema for users:

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->enum('role', ['admin', 'lecturer', 'student'])->default('student');
            $table->string('avatar')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

Also, here’s my configuration:

    'disks' => [

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
            'throw' => false,
        ],
    ],

I have changed from the validation from ‘avatar’ => ‘nullable|image|max:1024’, to above to accept what I was trying to test (a .png with size 5.44 KB)
Originally, I didn’t have $validatedData or array_merge as shown below:

 User::updateOrCreate(['id' => $this->userId], [
            'name' => $this->name,
            'email' => $this->email,
            'role' => $this->role,
            'avatar' => $this->avatar ? $this->avatar->store('avatars') : null,         
        ]);

and in edit function was $this->avatar = $user->avatar;
I discovered that the follwing was still not working and displayed “The avatar field must be an image.” Despire update to above, it was still somehow stored in storage/app/private/livewire-tmp with random name CXZNomzyXgBbPLlHwQQNdXbZypmQ4y-metaTmV0U2F2dnkgTG9nbyAxIHcgZ3JhZGllbnQucG5n-.png instead of app/public with filenmae like avatar-1699458603.jpg

if ($this->avatar) {
    $validatedData['avatar'] = $this->avatar->store('avatars', 'public');
}

New contributor

A_C is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật