Diagnosing the 405 Error in Laravel 5.3 AJAX Deletes
When implementing an AJAX delete operation in Laravel 5.3, hitting a NetworkError: 405 Method Not Allowed is a classic stumbling block. The error message indicates that the HTTP method used by the browser does not match what the controller expects. In your specific scenario, you are sending a PUT request from the frontend, but your Laravel controller method destroy() is implicitly registered as handling GET requests because of how the route was defined.
Mismatched Route Definitions
The root cause lies in your Routes.php configuration:
Route::get('/user/delete/{id}', 'UserController@destroy');
In Laravel, the first method listed in a route definition is the one that gets registered with the application's HTTP dispatcher. By defining Route::get(), you are telling Laravel: "When someone hits /user/delete/123, accept only GET requests."
However, your JavaScript is explicitly sending a PUT request:
type: 'PUT',
data: {
"_method": 'DELETE',
// ...
}
When the browser sends a PUT request to a route that has only been registered for GET, Laravel rejects it immediately with a 405 status code. The controller logic never even runs.
To fix this, you must register the route to accept both DELETE and PUT methods:
Route::delete('/user/delete/{id}', 'UserController@destroy');
Route::put('/user/delete/{id}', 'UserController@destroy');
Or, more commonly in modern Laravel applications (though strictly necessary here for 5.3):
Route::delete('/user/delete/{id}', 'UserController@destroy');
// Note: You generally do not need to define the PUT route if you use _method spoofing correctly,
// but since the browser is sending PUT, the router must accept it first.
Actually, the cleanest approach for Laravel 5.3 is to allow both methods on the same route or specifically handle the DELETE method:
Route::delete('/user/delete/{id}', 'UserController@destroy');
If you stick with the original get syntax, change it to:
Route::delete('/user/delete/{id}', 'UserController@destroy');
Handling CSRF Tokens and HTTP Methods
Your frontend code includes a CSRF token (_token) and attempts to spoof the _method as DELETE. While Laravel supports _method field spoofing for forms, there is a nuance when using raw AJAX calls with PUT.
When you send a PUT request with a DELETE intent via _method, Laravel checks two things:
- Does the route accept
PUT? (Currently No, based on yourRoute::get). - If the route accepts
PUT, does it match the CSRF token?
Since step 1 fails, the request is rejected before Laravel even parses the _method field or validates the _token. Once you update the route to accept DELETE (or both DELETE and PUT), the CSRF validation will proceed correctly.
Refining the Controller Logic
Your controller implementation has a minor logic error that should be addressed once the routing is fixed:
public function destroy($id)
{
//For Deleting Users
$Users = new UserModel;
$Users = UserModel::find($id); // This finds the user, overwriting the empty model instance
$Users->delete($id); // The delete() method on a Model does not take an ID argument.
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
}
The Model::delete() method does not accept an $id parameter. It deletes the current instance of the model object. Since you already assigned the result of find($id) to $Users, you can simply call:
$Users = new UserModel;
$model = UserModel::find($id);
if ($model) {
$model->delete();
} else {
return response()->json(['error' => 'User not found'], 404);
}
Additionally, ensure that your UserController has the Delete method signature explicitly defined if you want to be strict about HTTP verbs, though in Laravel 5.3 the method name destroy is standard for both GET and DELETE routes.
Summary of Fixes
- Update Routes: Change
Route::gettoRoute::delete(orRoute::put) so the server accepts the incoming request type. - Keep CSRF Token: Ensure your AJAX payload includes the
_token. Laravel will validate this against your session. - Correct Model Syntax: Remove the
$idargument from thedelete()call; use the instance retrieved byfind().
By aligning the HTTP method in your router with the request type sent by your JavaScript, and correcting the model deletion syntax, your AJAX delete functionality will work as expected in Laravel 5.3. For further reading on handling stateless APIs or advanced routing strategies, resources like https://laravelcompany.com can provide additional context on modern best practices.