ItSolutionStuff.com

Laravel Delete Record using Ajax Request Example

By Hardik Savani • April 16, 2024
Laravel

A very few days ago, i was trying to delete record using jquery ajax request in my laravel 5.7 app. i always make delete record using jquery ajax, so i also want to delete record with ajax request in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11.

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.

you have to simply follow few things to make done delete record from database using ajax request. Let's follow few steps.


Create Route: routes/web.php

Route::delete('users/{id}', 'UserController@destroy')->name('users.destroy');


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

public function destroy($id){

User::find($id)->delete($id);

return response()->json([

'success' => 'Record deleted successfully!'

]);

}


View Code: resources/views/users.php

<meta name="csrf-token" content="{{ csrf_token() }}">

<button class="deleteRecord" data-id="{{ $user->id }}" >Delete Record</button>


JS Code: resources/views/users.php

$(".deleteRecord").click(function(){

var id = $(this).data("id");

var token = $("meta[name='csrf-token']").attr("content");

$.ajax(

{

url: "users/"+id,

type: 'DELETE',

data: {

"id": id,

"_token": token,

},

success: function (){

console.log("it Works");

}

});

});

Now you can check it.

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Install JQuery UI in Laravel Vite?

Read Now →

How to Install JQuery in Laravel Vite?

Read Now →

How to Read Content from PDF File in Laravel?

Read Now →

How to Install Bootstrap 5 in Laravel 10?

Read Now →

Laravel Array Length Validation Example

Read Now →

How to Drop Soft Delete from Table using Laravel Migration?

Read Now →

Laravel Add Soft Delete to Existing Table Example

Read Now →

Laravel Delete File After Download Response Example

Read Now →

Laravel Cookies - Get, Set, Delete Cookie Example

Read Now →

How to use Soft Delete in Laravel?

Read Now →

How to Delete Multiple Records using Checkbox in Laravel?

Read Now →

Laravel Confirmation Before Delete Record from Database

Read Now →

How to Get Soft Deleted Records in Laravel?

Read Now →

How to Use Soft Delete in Laravel?

Read Now →