Laravel React profile picture upload

434 Views Asked by At

I want upload profile picture in laravel using reactjs . but this not work an I have Error. my code:

Route: Route::post('/profile', [ProfileController::class, 'update'])->name('profile.update'); ProfileUpdateRequest:

public function rules()
    {
        return [
            'name' => ['string', 'max:255'],
            'email' => ['email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id)],
            'avatar' => ['mimes:jpg,jpeg,png,bmp' ,'nullable'],
            
        ];
    }

In User DB avatar is : $table->string('avatar')->nullable(); React Codes: UpdateProfileInformation jsx:

const user = usePage().props.auth.user;
    const { data, setData, post } = useForm({
        name: user.name,
        email: user.email,
        avatar : null,
    });
    const submit = (e) => {
        e.preventDefault();
        post(route('profile.update'));
        setData("avatar" ,null)
    };
return(
 <form onSubmit={submit}  enctype="multipart/form-data">
                    <TextInput
                        id="name"
                        label="Name"
                        value={data.name}
                        handleChange={(e) => setData('name', e.target.value)}
                        autoComplete="name"
                    />
                    <TextInput
                        id="email"
                        type="email"
                        label="Email"
                        value={data.email}
                        handleChange=""
                        disabled
                        className="text-white"
                        autoComplete="email"
                    />
                    <TextInput id="avatar" type="file" label="Avatar" name="avatar"
                               handleChange={(e) => setData('avatar', e.target.avatar[0])}
                    />
                    
                <div className="flex items-center justify-around mt-4">
                    <PrimaryButton className="ml-4">Save</PrimaryButton>
            </form>
);

ProfileController:

public function update(ProfileUpdateRequest $request)
    {
        $request->user()->fill($request->validated());
            if ($request->has('avatar')){
                $filename = time().'.'.$request->avatar->getClientOriginalExtension();
                $request->avatar->move(public_path('avatar', $filename));
                User::update(['avatar' => $filename])->save();
            }

        $request->user()->save();

        return Redirect::route('profile.edit');
    }

Error: Call to a member function getClientOriginalExtension() on null. And picture Dosnot upload. because return null.

2

There are 2 best solutions below

4
On

Try this code.

if ($request->hasFile('avatar')){
    $filename = time().'.'.$request->file('avatar')->getClientOriginalExtension();
    $request->file('avatar')->move(public_path('avatar', $filename));
    User::update(['avatar' => $filename])->save();
}

Let me know if this works or not.

0
On

In React Component

const {data, setData, post, processing, errors, reset} = useForm({
    ...........
    avatar   : '',
    ...........
});

useEffect(() => {
    return () => {
        reset(.........,'avatar');
    };
}, []);

const submit = (e) => {
    e.preventDefault();
    post(formUrl);
};
<form onSubmit={submit} className="........." encType={`multipart/form-data`}>
  ..........
  <TextInput
      type={'file'}
      id={`avatar`}
      name={`avatar`}
      className={`.........`}
      onChange={(e) => setData('avatar', e.target.files[0])}
  />
  ..........
</form>

In Contoller

$storageFolder = 'avatar';
if($request->hasFile('avatar')){
    $file = $request->file('avatar');
    $fileName =  Str::random(5).'__'.date('d_m_y_h_i_s').'.'.$file->getClientOriginalExtension();
    Storage::disk('public')->putFileAs($storageFolder, $file,$fileName);
    $fileNameWithPath = 'storage/'.$storageFolder.$fileName;
}else{
    $fileNameWithPath = null;
}

YourModelName::updateOrCreate([
 .......
],[
    'avatar' => $fileNameWithPath,
    .........
]);

This is just to give you an idea how upload works with react and laravel