Laravel Advance | Delete record using ajax request in Laravel Example

Raviya Technical
1 min readJan 27, 2022

A very a few days ago, I was trying to delete records using jquery ajax request in my laravel 5.7 app. I always make delete records using jquery ajax, so I also want to delete records with ajax requests in laravel 5, laravel 6, laravel 7, and laravel 8.

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

you have to simply follow a few things to make done delete records from the database using ajax request. Let’s follow a 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…

--

--