jabrij93's avatar

After clicking a delete button, it redirects me to other page

After clicking a delete button on the images uploaded in the upload images or upload documents section, it redirects me to the 'produk.index' page. For the context, only 5 maximum uploads are allowed in upload images or upload documents section. Sometimes when I've uploaded 3 - 10 uploads, and when I tried to delete the images/documents, it will trigger the button where form is submitted with case 'create' and thus store the data and redirects me to the produk.index page as set in the code. I wonder what is happening here ? Below are my code,

const handleSubmit = async (e) => {
        e.preventDefault();

        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({
                text: error,
                icon: "error",
            });
        }
    };
<form method={"post"} onSubmit={handleSubmit}>
            <h3 className={"font-bold text-xl mb-4"}>
                {action === "create" ? "Daftar" : "Kemaskini"} Produk
            </h3>

           .........


                <div className={"col-span-2"}>
                    <InputLabel
                        value={"Muat Naik Gambar"}
                        className={"mb-2 font-bold text-base"}
                        required={false}
                    />

                    <InputError
                        message="Format: PNG, JPG, JPEG | Size: Max 2 MB"
                        className="mt-1"
                        text-align="right"
                    />

                    <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",
                        ]}
                    />
                    <InputError message={errors.images} />
                </div>

                <div className={"col-span-2"}>
                    <InputLabel
                        value={"Muat Naik Dokumen Sokongan"}
                        className={"mb-2 font-bold text-base"}
                    />

                    <InputError
                        message="Format: PNG, JPG, JPEG dan PDF | Size: Max 2 MB"
                        className="mt-1"
                        text-align="right"
                    />

                    <FileUpload
                        uploadedFiles={product_documents?.flatMap(
                            (file) => file
                        )}
                        product={product}
                        action={action}
                        setData={setData}
                        onError={(error) => {
                            Swal.fire({
                                text: error,
                                icon: "error",
                            });
                        }}
                        name="documents"
                        buttonText="Muat Naik"
                        allowedFileTypes={[
                            "application/pdf",
                            "image/png",
                            "image/jpg",
                            "image/jpeg",
                        ]}
                        required={false}
                    />
                    <InputError message={errors.documents} />
                </div>

             .............

route

Route::prefix('jualan')->group(function () {
        //Laporan
        Route::get('/senarai-jualan', [SalesController::class, 'index'])->name('senarai-jualan.index');
        //Laporan Hasil Jualan
        Route::get('/laporan-hasil-jualan', 'App\Http\Controllers\LaporanHasilJualanController@index')->name('laporan-hasil-jualan');
        //Produk
        Route::prefix('produk')->group(function () {
            Route::get('/', [ProductsController::class, 'index'])->name('produk.index');
            Route::get('/create', [ProductsController::class, 'create'])->name('produk.create');
            Route::post('/', [ProductsController::class, 'store'])->name('produk.store');
            Route::get('/{produk}', [ProductsController::class, 'show'])->name('produk.show');
            Route::get('/edit/{produk}', [ProductsController::class, 'edit'])->name('produk.edit');
            .............

controller

public function create()
    {
        $categories = DB::table('kategori_jualan')->get();
        $types = DB::table('jenis_jualan')->get();

        return Inertia::render('Produk/Create', [
            'categories' => $categories,
            'types' => $types
        ]);
    }
public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'images.*' => 'image|max:2048', // max file size: 2MB
            'documents.*' => 'file|max:2048', // max file size: 2MB
        ]);

        $product = DB::table('products')->insertGetId([
            'name' => $request['name'],
            'description' => $request['description'],
            'type_id' => $request['type_id'],
            'category_id' => $request['category_id'],
            'price' => $request['price'],
            'start_date' => $request['start_date'],
            'end_date' => $request['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++;
            }
        }

        // handle document uploads
        if ($request->hasFile('documents')) {
            $i = 1;
            foreach ($request->file('documents') as $document) {
                $name = $request['name'] . '-' . $i;
                $now = new DateTime();
                $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $i . '.' . $document->getClientOriginalExtension();
                //$fileName = Str::slug($request['name']) . '-' . time() . '.' . $document->getClientOriginalExtension();
                $path = $document->storeAs('public/Product/Documents', $fileName);
                DB::table('product_documents')->insert([
                    'product_id' => $product,
                    'name' => $name,
                    'file_path' => Storage::url($path),
                    'created_at' => now(),
                ]);
                $i++;
            }
        }

        return Redirect::route('produk.index');
    }

public function destroy($id)
    {
        // delete product images
        DB::table('product_images')->where('product_id', $id)->delete();

        // delete product documents
        DB::table('product_documents')->where('product_id', $id)->delete();

        // delete product
        DB::table('products')->where('id', $id)->delete();
    }
0 likes
1 reply
LaryAI's avatar
Level 58

The issue seems to be that the delete button is submitting the form with the case 'create' action, which is causing the data to be stored and redirecting to the produk.index page. To fix this, you can modify the handleSubmit function to check if the form is being submitted from the delete button, and if so, call a separate function to handle the delete request. Here's an example:

const handleSubmit = async (e) => {
    e.preventDefault();

    const deleteButton = e.nativeEvent.submitter;
    if (deleteButton && deleteButton.name === 'delete') {
        // handle delete request
        const productId = deleteButton.value;
        await deleteProduct(productId);
        return;
    }

    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({
            text: error,
            icon: "error",
        });
    }
};

const deleteProduct = async (productId) => {
    try {
        await axios.delete(`/jualan/produk/${productId}`);
        Swal.fire({
            text: "Produk berjaya dipadam",
            icon: "success",
        });
        // reload page or update product list
    } catch (error) {
        Swal.fire({
            text: error,
            icon: "error",
        });
    }
};

In the handleSubmit function, we first check if the form is being submitted from a delete button by checking the nativeEvent.submitter property. If it exists and has a name attribute of 'delete', we extract the value attribute (which should be the product ID) and call the deleteProduct function.

The deleteProduct function sends a DELETE request to the server using Axios, passing in the product ID as a parameter. If the request is successful, we display a success message using SweetAlert and reload the page or update the product list. If there's an error, we display an error message.

Note that you'll need to modify the delete button in your HTML to include a name attribute of 'delete' and a value attribute of the product ID, like this:

<button type="submit" name="delete" value="{{ $product->id }}">Delete</button>

Please or to participate in this conversation.