Laravel

How to Delete Record using ajax call with Laravel

How to Delete Record using ajax call with Laravel

We work on projects with the admin panel every day. In which we mostly use data tables and we need to delete the record from the data table without page refresh.

So, today I will show you how to extract a record using Ajax. It’s very easy to integrate.

Let’s take one example. I have a Category data table and I want to delete one category from the table without refreshing the page. Now, what am I doing for that? First of all, I add a class for the listen to a click event into the delete button and it says delete-btn.

See the following image for where I added a class.

1 (2)

I used SweetAlert for the confirmation popup. let add sweet alert’s CSN into the index.blade.php.

				
					<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css"> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
				
			

Let’s declare routes of the delete record.

				
					<script>let categoryUrl = '{{route('categories.index')}}'; </script>
				
			

Next steps, I’m going to listen to the click event of the delete button. one more thing does not forget to add the record id into the data attribute to the delete button. see the above image for it. I highlighted it with a yellow line.

So the general practices we use in Laravel is to write the following code to listen to a click event and delete a record,

				
					$(document).on('click', '.delete-btn', function (event) {             
           const id = $(event.currentTarget).data('id');

  swal({ 
      title: 'Delete !',                     
      text: 'Are you sure you want to delete this Category" ?',                     
      type: 'warning',                    
      showCancelButton: true,                     
      closeOnConfirm: false,                     
      showLoaderOnConfirm: true,                     
      confirmButtonColor: '#5cb85c',                     
      cancelButtonColor: '#d33',                     
      cancelButtonText: 'No',                     
      confirmButtonText: 'Yes',                 },                 
          function () {                    
                   $.ajax({                 
                       url: categoryUrl + '/' + id,                 
                       type: 'DELETE',                 
                       DataType: 'json',                 
                       data:{"_token": "{{ csrf_token() }}"},                 
                       success: function(response){                     

                              swal({                                 
                                  title: 'Deleted!',                                 
                                  text: 'Category has been deleted.',                                 
                                  type: 'success',                                 
                                  timer: 2000,                             
                              });                     
  $('#categoryTbl').DataTable().ajax.reload(null, false);                 
              },                 
               error: function(error){                     
               swal({                                 
                   title: 'Error!',                                 
                   text: error.responseJSON.message,                                 
                   type: 'error',                                 
                   timer: 5000,                             
              })                     
            }             
        });                 
    });         
});
				
			

Now we are done with the front-end side and need to look into it backend side.

Let’s declare the destroy method into the category Controller. I hope are you generating crud with InfyOm Laravel Generator. so, the Destroy method and routes are there. If not please create a route. if the destroy method is there then need to change the response of that method.

The destroy method code looks like,

				
					 public function destroy($id)     { 
        $category = $this->categoryRepository->find($id);
        if (empty($category)) {
            Flash::error('Category not found');

            return $this->sendError('Category not found.');
        }

        $this->categoryRepository->delete($id);

        return $this->sendSuccess('Category deleted successfully.');
    }
				
			
Share On: