Mr. Developer Mr. Developer - 3 months ago 248
Ajax Question

How to delete record in laravel 5.3 using ajax request?

I'm trying to delete record using ajax in laravel 5.3, i know this is one of the common question and there is already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me same error

NetworkError: 405 Method Not Allowed
. I tried to do this task by different angle but i'm stuck and could not found where i'm wrong, that's why i added this question for guideline.

I'm trying following script for deleting the record.

Controller.php

public function destroy($id)
{ //For Deleting Users
$Users = new UserModel;
$Users = UserModel::find($id);
$Users->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
}


Routes.php

Route::get('/user/delete/{id}', 'UserController@destroy');


In View

<button class="deleteProduct" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >Delete Task</button>


App.js

$(".deleteProduct").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'PUT',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});

console.log("It failed");
});


When i'm click on delete button it returning me error
NetworkError: 405 Method Not Allowed
in console. Without ajax same delete function is working properly.

Can anyone guide me where i'm wrong that i can fix the issue, i would like to appreciate if someone guide me regarding this. Thank You..

Answer

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;
$Users = UserModel::find($id);
$Users->delete($id);

can be written as:

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