amandajgby's avatar

Delete and update data at the same time in Laravel Ajax dynamic form

I have a form divided into two sections, a regular product form and a dynamic form for the product details below the regular one. I can successfully update or create new data. Now I tried using Ajax for the deletion process.

However, when I tried to delete a row in the dynamic form, the row had not been deleted. When I click submit to update all of the data in product form (the regular form and the dynamic one), it returns the success message for the deletion process. Still, the data has not been deleted from the database.

The controller works fine when I update old data, create new data without updating it, and create new data + update the old one. It just does not work when I try to do the delete process. What I want to achieve is to keep updating the existing data while deleting the removed data.

Form Design

View Code

	<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

    <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: 'Are you sure?',
    text: "Do you want to delete this?",
    icon: 'warning',
    showCancelButton: true,
    cancelButtonText: 'No',
    confirmButtonText: 'Delete!'
}).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();
 });

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);

Please help because I'm still a beginner at making dynamic forms like this. I appreciate your help.

0 likes
3 replies
EngMohammed40's avatar

For deleting you can use this approach: Define an input hidden with name for example "keep_ids" and it will has all the ids of the dynamic parts. Whenever a user deletes a row an id of the array "keep_ids" will disapear. In the controller you can do something like this: MyModel::whereNotIn($request->keep_ids)->delete();

jlrdw's avatar

Clear the fields after a successful delete.

amandajgby's avatar

@jlrdw, do you mean by delete all the records when deleting them and then recreate the records when the update process is complete?

Please or to participate in this conversation.