Unable to create Delete action in Laravel.
I am getting Not Found
or Token mismatch
errors all the time.
My controller:
class TranslationController extends Controller
{
public function destroy($id)
{
//$id = 1;
/*$translation = Translation::find($id);
$translation->delete();*/
}
....
}
Ajax call:
/* Delete given translation */
var url = "translation";
var id = 1;
$.ajax({
method: 'DELETE',
url: url + '/' + id,
// data: {'id': id, '_token': token},
success: function() {
}
});
This would give: TokenMismatchException in VerifyCsrfToken.php line 53:
If I try:
url: url + '/' + id,
data: {'_token': token}, // token is equal to csrf_token
I have: NotFoundHttpException in Controller.php line 269:
Routes:
Route::controller('translation', 'TranslationController');
Otherwise I am using Laravel 5 default Middleware, I have not changed anything related to csrf.
NotFoundHttpException
means that either the route for the particular request with the particular HTTP verb has not been specified, or the action (i.e. the controller method) that is mapped to the verb for the route is wrongly implemented.
Since you've mentioned in the post that the TranslationController
is defined as an implicit controller,
Route::controller('translation', 'TranslationController');
and from the controller code you've posted, it's quite obvious that you have not defined the verb for the destroy
method in your controller TranslationController
.
If you do a php artisan route:list
in your projects root directory with a terminal/command line interface, you'll see the listing of the registered HTTP verbs, mapping to the corresponding URIs, and the actions.
To define a particular method in an implicit controller, the verb (GET
, PUT
, POST
, DELETE
) should precede the actual function name.
Make sure that the destroy
method looks like the following in your controller:
public function deleteDestroy($id){
//delete logic for the resource
}
Note:
Laravel by default requires that the csrf
token is passed along with a particular RESTful request, so do not remove data: {'_token': token}
from your AJAX
call.
Forgot to mention that the url
in your AJAX call should also be changed to the following in order to work, because this is how Laravel's implicit controllers define the route for a DELETE
request:
var url = "translation/destroy";
Here is documentation about method spoofing. You need to send a POST ajax request with _method
field set to DELETE
$.ajax({
method: 'POST',
url: url + '/' + id,
data: {
'id': id,
'_token': token,
'_method' : 'DELETE'
},
success: function() {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With