Delete Record using Ajax Request in Laravel 7

Today i will show you how to delete data using ajax request in Laravel 7. you have to simply follow few things to make done delete record from database using ajax request.

In this tutorial i will simply delete a column record using ajax request. You will learn from this tutorial about Laravel destroy using ajax request.If you don't know how to do it, just follow below things.

You know that when we send ajax request to server to delete data, then page won't refresh but our data will be deleted. How cool, isn't it? We will use POST request to delete data from database using ajax request.

we will create delete route with controller method(we will write delete row code using database model) and write jquery ajax code with delete post request. we also pass csrf token in jquery ajax request, otherwise it will return error like delete method not allowed.

 

delete-record-using-ajax-request-in-laravel

So let's start delete row using ajax in laravel tutorial. 

Read also : Form Validation with File Upload in Laravel 6

Create Route: routes/web.php

Route::delete('/addcompany/{id}', '[email protected]')->name('company.destroy');

Controller Method: app/Http/Controllers/CompanyController.php

public function destroy($id){
   
      $company = Company::find($id);
      $company->delete();
      return response()->json([
        'message' => 'Data deleted successfully!'
      ]);

}

View Code: resources/views/company.blade.php

Read also : Ajax Login Form Using jQuery, PHP And MySQLi

JS Code: resources/views/company.blade.php


$(document).ready(function () {

 $("body").on("click","#deleteCompany",function(e){

    if(!confirm("Do you really want to do this?")) {
       return false;
     }

    e.preventDefault();
    var id = $(this).data("id");
    // var id = $(this).attr('data-id');
    var token = $("meta[name='csrf-token']").attr("content");
    var url = e.target;

    $.ajax(
        {
          url: url.href, //or you can use url: "company/"+id,
          type: 'DELETE',
          data: {
            _token: token,
                id: id
        },
        success: function (response){

            $("#success").html(response.message)

            Swal.fire(
              'Remind!',
              'Company deleted successfully!',
              'success'
            )
        }
     });
      return false;
   });
    

});

Hope it can help you.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website