Delete Ketika Update Dynamic Form Laravel

Saya punya dynamic form dengan design seperti ini: https://i.sstatic.net/1ppsrF3L.png. Dynamic form ini terletak di bawah form regular (menjadi satu) dan nantinya akan di-update bersamaan dengan data form regulernya.

Sejauh ini, saya sudah mampu meg-update data lama, update data lama + menambah data baru, dan menambah data baru di dynamic form saya. Namun, saat saya mencoba menghapus 1 row data dengan Ajax, row-nya tidak terhapus, baik di form maupun di database, padahal muncul return success message.

Saya ingin form-nya bisa tetap di-update saat ada data baru maupun tidak, dan saat ada row yang di-delete.

View

<form id="form1" class="ecommerce-form action-buttons-fixed" action="{{ route('products.update',$products->id) }}" method="POST" enctype="multipart/form-data">
   @csrf
   @method('PUT')

   <!--Regular form field here-->

   <!--Dynamic Form-->
   @foreach($specifications as $i => $spec)
       <input type="hidden" name="specifications[{{$i}}][id]" value="{{$spec->id}}">

       <div class="form-group row justify-content-center product-spec-row pb-3" id="index_{{ $spec->id }}">
          <div class="col-xl-6">
             <label class="control-label">Name</label>
             <input type="text" class="form-control form-control-modern @error('spec_name') is-invalid @enderror" placeholder="Specification Name" name="specifications[{{$i}}][spec_name]" value="{{$spec->spec_name}}" />

           </div>
           <div class="col-xl-6">
               <a href="javascript:void(0);" class="product-spec-remove text-color-danger float-end">Remove</a>
               <label class="control-label">Value(s)</label>
               <textarea class="form-control form-control-modern @error('value') is-invalid @enderror" name="specifications[{{$i}}][value]" rows="4" placeholder="Enter some text">{{$spec->value}}</textarea>
           </div>
       </div>

      @endforeach

      </div>
      <div class="row justify-content-center mt-4">
         <div class="col-xl-9 text-end">
            <a href="#" class="product-spec-add-new btn btn-primary btn-px-4 btn-py-2">+ Add New</a>
        </div>
      </div>
     <!--Dynamic Form End-->       

     </form>

Script

$(document).on('click', '.product-spec-remove', function(e) {
        e.preventDefault();
        let spec_id = $(this).data('id');
        let token   = $("meta[name='csrf-token']").attr("content");

        Swal.fire({
            title: 'Apakah Kamu Yakin?',
            text: "ingin menghapus data ini!",
            icon: 'warning',
            showCancelButton: true,
            cancelButtonText: 'TIDAK',
            confirmButtonText: 'YA, HAPUS!'
        }).then((result) => {
            if (result.isConfirmed) {

                console.log('test');

                //fetch to delete data
                $.ajax({

                    url: `/specdelete/${spec_id}`,
                    type: "DELETE",
                    cache: false,
                    data: {
                        "_token": token
                    },
                    success:function(response){

                        //show success message
                        Swal.fire({
                            type: 'success',
                            icon: 'success',
                            title: `${response.message}`,
                            showConfirmButton: false,
                            timer: 3000
                        });
                    }
                });
            }
        })

        $(`#index_${spec_id}`).remove();
       // $(this).closest('.product-spec-row').remove();
    });
</script>

Controller

foreach ($request->specifications as $key => $specs) {

            // Update
            if (isset($specs['id']) && $specs['id']) {
                $data = ProductSpecification::where('id', $specs['id'])->first();
                $data->product_id = $products->id;
                $data->spec_name = $specs['spec_name'];
                $data->value = $specs['value'];
                $data->updated_by = Auth::user()->id;
                // Create
            } else {
                $data = new ProductSpecification();
                $data->product_id = $products->id;
                $data->spec_name = $specs['spec_name'];
                $data->value = $specs['value'];
                $data->created_by = Auth::user()->id;
            }
                ProductSpecification::where('id', $id)->delete();

                // return response
                return response()->json([
                     'success' => true,
                     'message' => 'Detail Produk Berhasil Dihapus!.',
                 ]);

            $data->save();
        }

Route

Route::post('/specdelete/{id}', [App\Http\Controllers\ProductsController::class, 'deleteSpecification'])->name('deletespecification');
Route::resource('products', ProductsController::class);

Mohon bantuannya, karena saya baru pertama kali membuat dynamic form yang datanya perlu bisa di-delete. Terima kasih banyak ^^

avatar amandajgby
@amandajgby

2 Kontribusi 0 Poin

Dipost 3 minggu yang lalu

Belum ada Jawaban. Jadi yang pertama Jawaban

Login untuk ikut Jawaban