Oct 15, 2024
0
Level 1
updating image problem Laravel 11, Intertia, React js
I have problem while updating image when I store image it works fine but I when I try to update the image even the $request returns null, and if I do not update the image and update other fields it updates other fields and keep the old image: Here is my store, how I send it from front end
public function store(Request $request)
{
dd($request->all());
// Validate the request inputs including the image
$fields = $request->validate([
// 's_no' => ['required'],
'name' => ['required'],
'age' => ['nullable'],
'address' => ['nullable'],
'phone' => ['nullable'],
'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif', 'max:2048'], // Validation for image type and size
'qualification' => ['nullable']
]);
$maxSerialNo = LibraryRegistration::max('s_no'); // Find the highest serial number
$newSerialNo = $maxSerialNo ? $maxSerialNo + 1 : 1000; // Start at 1000 if there are no records
// Step 2: Check if the serial number already exists (optional, though it should be unique)
$exists = LibraryRegistration::where('s_no', $newSerialNo)->exists();
if ($exists) {
return redirect()->back()->withErrors(['s_no' => 'Serial number already exists!']);
}
// Add the unique serial number to the fields array
$fields['s_no'] = $newSerialNo;
// Check if the request has an image
if ($request->hasFile('image')) {
// dd($request->file('image')); // Dump the image details
// Store the image in the 'public/images' folder and get the path
$imagePath = $request->file('image')->store('images', 'public');
// Save only the path or image name to the fields array
// $fields['image'] = $imagePath; // If you want the full path, use this.
$fields['image'] = basename($imagePath); // If you only want to save the filename.
}
// Create the new library registration record with the validated fields
LibraryRegistration::create($fields);
// Redirect back to the registrations list or any preferred route
return redirect('/registrations')->with('message', 'Library Registration created successfully.');
}
this is my update function in controller
public function update(Request $request, $id)
{
$registration = LibraryRegistration::findOrFail($id);
// Validate the request inputs conditionally
$fields = $request->validate([
'name' => ['sometimes', 'required'],
'age' => ['nullable'],
'address' => ['nullable'],
'phone' => ['nullable'],
'qualification' => ['nullable']
]);
// Check if the request has an image
if ($request->hasFile('image')) {
// Validate the image type and size
$request->validate([
'image' => ['required', 'image', 'mimes:jpeg,png,jpg,gif', 'max:2048']
]);
// Remove the old image from storage if it exists
if ($registration->image) {
Storage::delete('public/images/' . $registration->image);
}
// Store the new image in the 'public/images' folder and get the path
$imagePath = $request->file('image')->store('images', 'public');
$fields['image'] = basename($imagePath); // Save only the filename
} else {
// If no image is sent, keep the existing image
$fields['image'] = $registration->image;
}
// Update the library registration record with new or retained data
$registration->update(array_merge($registration->toArray(), $fields));
// Redirect or return success message
return redirect('/registrations')->with('message', 'Library Registration updated successfully.');
}
the way is send from front end to back end. in my edit file
const { data, setData, put, errors, processing } = useForm({
name: registration?.name || "",
age: registration?.age || "",
address: registration?.address || "",
phone: registration?.phone || "",
image: registration?.image || null,
qualification: registration?.qualification || "",
});
const handleChange = (e) => {
const { name, value, type, files, checked } = e.target;
console.log("files" , files)
setData((prev) => ({
...prev,
[name]:
type === "checkbox"
? checked
: value,
}));
};
const handleFileChange = (e) => {
const file = e.target.files[0]; // Get the file
console.log("file" , file)
if (file) {
setData((prevData) => ({
...prevData,
image: file, // Store the file object in state
}));
}
console.log("Data" , data)
};
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData();
// Append the image file to the formData
// Append other fields to the formData
Object.keys(data).forEach((key) => {
if (key !== 'image') {
formData.append(key, data[key]);
}
});
if (data.image instanceof File) {
formData.append('image', data.image);
}
isEditMode ? put(url ,data
) : post(url);
};
<form
onSubmit={handleSubmit}
// method={`${isEditMode ? 'PUT' : 'POST'}`}
className="bg-white shadow-md rounded-lg p-8"
// encType="multipart/form-data"
>
<div className="grid grid-cols-3 gap-8 capitalize">
{fields.map(renderField)}
</div>
<div className="flex justify-end mt-8">
<button
type="submit"
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg focus:outline-none focus:ring-4 focus:ring-blue-300 disabled:bg-gray-400 disabled:cursor-not-allowed"
disabled={processing}
>
{isEditMode ? "Update" : "Create"}
</button>
</div>
</form>
Please or to participate in this conversation.