I posted this previously, but after checking the code back and dig deeper, I found the delete button code and thus I’ll post the updated info here.
Uploading the images has no problem but when deleting the uploaded images, it triggers the store button instead. I recorded the error here, https://youtu.be/Eq3Y8s2G2GE . I am wondering why is this happening ? I tried to change things here and there but it is still the same. The following are my code. Please help.
Storing the images initially
public function store(Request $request)
{
$data = $this->validate($request, [
'name' => 'required',
'description' => 'required|max:150',
'category_id' => 'required',
'type_id' => 'required',
'price' => 'required|numeric|min:0|not_in:0',
'start_date' => 'required',
'end_date' => 'required',
'is_active' => 'required',
'images.*' => 'image|max:2048', // max file size: 2MB
'documents.*' => 'file|max:2048', // max file size: 2MB
]);
$product = DB::table('products')
->insertGetId([
'name' => $data['name'],
'description' => $data['description'],
'type_id' => $data['type_id'],
'category_id' => $data['category_id'],
'price' => $data['price'],
'start_date' => $data['start_date'],
'end_date' => $data['end_date'],
'is_password' => $request['is_password'],
'is_stamping' => $request['is_stamping'],
'created_at' => now(),
]);
// handle image uploads
if ($request->hasFile('images')) {
$i = 1;
foreach ($request->file('images') as $image) {
$name = $request['name'] . '-' . $i;
$now = new DateTime();
$fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $i . '.' . $image->getClientOriginalExtension();
//$fileName = Str::slug($request['name']) . '-' . time() . '.' . $image->getClientOriginalExtension();
$path = $image->storeAs('public/Product/Images', $fileName);
DB::table('product_images')->insert([
'product_id' => $product,
'name' => $name,
'file_path' => Storage::url($path),
'created_at' => now(),
]);
$i++;
}
}
}
return Redirect::route('produk.index');
}
Editing the uploaded images afterwards, deleting or adding more images
public function update(Request $request, $id)
{
$data = $this->validate($request, [
'name' => 'required',
'description' => 'required|max:150',
'category_id' => 'required',
'type_id' => 'required',
'price' => 'required|numeric|min:0|not_in:0',
'start_date' => 'required',
'end_date' => 'required',
'is_active' => 'required',
'images.*' => 'image|max:2048', // max file size: 2MB
'documents.*' => 'file|max:2048', // max file size: 2MB
]);
DB::table('products')
->where('id', $id)
->update([
'name' => $data['name'],
'description' => $data['description'],
'type_id' => $data['type_id'],
'category_id' => $data['category_id'],
'price' => $data['price'],
'start_date' => $data['start_date'],
'end_date' => $data['end_date'],
'is_active' => $data['is_active'],
'is_password' => $request['is_password'],
'is_stamping' => $request['is_stamping'],
'updated_at' => now(),
]);
// handle image uploads
if ($request->hasFile('images')) {
//DB::table('product_images')->where('product_id', $id)->delete();
//Storage::deleteDirectory('public/Product/Images/' . $id);
foreach ($request->file('images') as $image) {
$name = $request['name'] . '-' . $id;
$now = new DateTime();
$fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $id . '.' . $image->getClientOriginalExtension();
$path = $image->store('public/Product/Images/' . $fileName);
DB::table('product_images')->insert([
'product_id' => $id,
'file_path' => Storage::url($path),
'created_at' => now(),
]);
}
}
return Redirect::route('produk.index');
}
The button that gets triggered,
const formik = useFormik({
initialValues: {
name: action === "create" ? "" : `${data.name}`,
description: action === "create" ? "" : `${data.description}`,
category_id: action === "create" ? "" : `${data.category_id}`,
type_id: action === "create" ? "" : `${data.type_id}`,
price: action === "create" ? "" : `${data.price}`,
is_active: action === "create" ? "" : `${data.is_active}`,
start_date: action === "create" ? "" : `${data.start_date}`,
end_date: action === "create" ? "" : `${data.end_date}`,
// is_password: action === "create" ? "" : `${data.is_password}`,
// is_stamping: action === "create" ? "" : `${data.is_stamping}`,
},
validationSchema: validationSchema,
onSubmit: async (values) => {
try {
switch (action) {
case "create":
await post(route("produk.store"));
Swal.fire({
text: "Maklumat produk berjaya disimpan",
icon: "success",
});
break;
case "update":
await put(route("produk.update", product.id), data);
Swal.fire({
text: "Maklumat produk berjaya dikemaskini",
icon: "success",
});
break;
}
} catch (error) {
Swal.fire({
icon: "error",
title: "Oops...",
text: "Something went wrong!",
});
}
},
});
return (
<form method={"post"} onSubmit={formik.handleSubmit}>
....................
FileUpload component where the delete button lies in it
<FileUpload
uploadedFiles={product_images?.flatMap((file) => file)}
product={product}
action={action}
setData={setData}
onError={(error) => {
Swal.fire({
text: error,
icon: "error",
});
}}
name="images"
buttonText="Muat Naik"
allowedFileTypes={[
"image/png",
"image/jpg",
"image/jpeg",
]}
/>
Delete button to remove file upload when adding product
const removeFileUpload = (e, index) => {
const updatedFileUpload = [...fileUpload];
updatedFileUpload.splice(index, 1);
setFileUpload(updatedFileUpload);
setData(name, updatedFileUpload);
};
Delete button to remove img when editing/updating product
return (
...........
<button
onClick={() => removeFileUpload(index)}
className="outline-none border-none"
>
<FaTimes className="text-red-600" />
</button>
.....