How to delete record in laravel 5.3 using ajax request?
Instead of using Route::get
use Route::delete
.
In addition to that change the type: 'Put'
to type: 'DELETE'
in the ajax call.
P.S. This code
$Users = new UserModel; // Totally useless line$Users = UserModel::find($id); // Can chain this line with the next one$Users->delete($id);
can be written as:
UserModel::find($id)->delete();
Or even shorter:
UserModel::destroy($id);
Keep in mind that ->delete()
will fire an event while ::destroy()
will not.
Make sure to add this in the meta
tag of your view
<meta name="csrf-token" content="{{ csrf_token() }}">
In your Routes
, do this
Route::delete('/user/delete/{id}', 'UserController@destroy');
In your controller, do this
UserModel::destroy($id);
or
DB::table('table_name')->where('id', $id)->delete();
Make sure to check that the user who is deleting the account actually owns the account a.k.a run authorization test.
Since it's a delete
request, you would require to send the csrf_token
along with your ajax header as the official site states.https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token
Make sure to add this before the ajax call
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }});
Now send the request
$(".deleteProduct").click(function(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax( { url: "user/delete/"+id, type: 'delete', // replaced from put dataType: "JSON", data: { "id": id // method and token not needed in data }, success: function (response) { console.log(response); // see the reponse sent }, error: function(xhr) { console.log(xhr.responseText); // this line will save you tons of hours while debugging // do something here because of error } });});
I hope this helps.
$(".deleteProduct").click(function(){$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }});$.ajax({ url: "user/delete/"+id, type: 'DELETE', // Just delete Latter Capital Is Working Fine dataType: "JSON", data: { "id": id // method and token not needed in data }, success: function (response) { console.log(response); // see the reponse sent }, error: function(xhr) { console.log(xhr.responseText); // this line will save you tons of hours while debugging // do something here because of error }});
});