In my following code, I want to delete a photo from the system through AJAX but when making the request, it throws me the previous error
Error: The requested method DELETE is not allowed for the URL
my code is the following
Route:
Route::delete('tienda/productos/eliminarimagen/{id}', 'TiendaController@destroy')
Controller:
public function destroy($id)
{
$this->connection->db_connection();
$producto = VipArchivo::find($id);
$producto->delete();
Session::flash('message', 'Imagen eliminada');
return Redirect::to('tienda/productos/edit/'.$id.'');
}
And the AJAX:
function eliminaImg(values)
{
var id_foto = values;
var route = 'http://localhost/tienda/productos/eliminarimagen/'+id_foto+'';
var token = $('#token').val();
swal({
title: "Eliminar foto",
text: "¿Está seguro de eliminar esta foto?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Sí, eliminar!",
cancelButtonText: "Cancelar",
closeOnConfirm: false },
function(){
console.log(id_foto);
$.ajax({
url:route,
headers: {'X-CSRF-TOKEN':token},
type:'DELETE',
dataType:'json',
success: function(){
console.log('eliminó');
}
})
});
}
It can happen because you don't have the DELETE method enabled in CORS. Assuming you have a version of laravel greater than 5.0.
What you need to do is create a Cors middleware
php artisan make:middleware Cors
Open the App->Http->Middleware->Cors.php file that was created, and in the handle function define the following
You can delete the methods that are not useful to you, the one that is useful to you now is DELETE
In the App -> Http -> Kernel.php file, go to $middleware and add the following line:
\App\Http\Middleware\Cors::class,
inside $routeMiddleware add the following line
Finally, you must define the middleware to use, grouping the routes you want to access by the methods you need, whether in api or web