Laravel 8.x Delete Record Using Ajax Request Example

Today i will show you how to delete data using ajax request in Laravel 8. 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}', 'CompanyController@destroy')->name('company.destroy');

 

Paste this below code in your controller to delete data in laravel using ajax request.

app/Http/Controllers/CompanyController.php

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

}

 

Paste this below code in your blade view file to delete data in laravel using ajax request.

resources/views/company.blade.php

 

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

 

 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.

 

#ajax-request #laravel #ajax #laravel-6 #delete