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.
Try this code.
Let me know if this works or not.