CONTEXTO. Estoy trabajando en Laravel 8 y uso el plugin DataTables para mostrar en pantalla los registros de una base de datos.
PROBLEMA. Cuando presiono el botón borrar de un registro en específico, el registro sí se borra, bien, pero la consola del navegador devuelve este error: "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST", y por tanto Javascript se rompe y nunca salta el alert de que el registro fue borrado. Y si cambio el tipo de petición a POST, ¡el error me dice que no es soportado POST y sí DELETE!
PREGUNTA: ¿qué estoy pasando haciendo mal?
RUTA
Código PHP:
Route::resource('animal', 'AnimalController');
Código PHP:
public function destroy($id)
{
$animal = DB::select('CALL sp_destroy_animal(?)', [$id]);
return back();
}
Código PHP:
jQuery('#BTNeliminar').click(function(e){
e.preventDefault();
var url = '{{ route("animal.destroy", ":xxx") }}';
url = url.replace(':xxx', animalID);
jQuery.ajax({
"url": url,
"type": 'DELETE',
"data": {
"_token": "{{ csrf_token() }}"
},
beforeSend: function() {
jQuery('#BTNeliminar').text('Eliminando...');
},
success: function(data) {
setTimeout(function() {
// Desaparecemos el modal
jQuery('#modalEliminar').modal('hide');
// Que salte el toast como en Android
toastr.warning('El registro '+animalID+' fue eliminado correctamente.', 'Eliminar registro', {timeOut:3000});
jQuery('#tablaAnimal').DataTable().ajax.reload();
}, 100);
}
});
});
Código PHP:
Route::resource('animal', 'AnimalController');
RUTA
Route::get('animal/eliminar/{id}', [AnimalController::class, 'destroy'])->name('animal.destroy');
VISTA
jQuery('#BTNeliminar').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'animal/eliminar/'+animalID,
"data": {
"_token": "{{ csrf_token() }}"
},
beforeSend: function() {
jQuery('#BTNeliminar').text('Eliminando...');
},
success: function(data) {
setTimeout(function() {
// Desaparecemos el modal
jQuery('#modalEliminar').modal('hide');
// Que salte el toast como en Android
toastr.warning('El registro '+animalID+' fue eliminado correctamente.', 'Eliminar registro', {timeOut:3000});
jQuery('#tablaAnimal').DataTable().ajax.reload();
}, 100);
}
});
});
¡Cualquier ayuda es bienvenida!