Error deleting a record in laravel

0

In my next code, I want to delete a picture of the system using AJAX but at the time of making the request, I throw the previous error

  

Error: The requested method DELETE is not allowed for the URL

my code is as follows

Route:

Route::delete('tienda/productos/eliminarimagen/{id}', 'TiendaController@destroy')

Driver:

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ó');
                }

            })
        });
}
    
asked by BorrachApps Mex 28.06.2017 в 16:33
source

1 answer

0

It can happen because you have not enabled the DELETE method in CORS. Assuming you have a laravel version higher than 5.0.

What you should 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

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

    }

You can delete the methods that are not useful to you, the one that is useful now is DELETE

In the file App - > Http - > Kernel.php Go to $ middleware and add the following line: \App\Http\Middleware\Cors::class,

in $ routeMiddleware add the following line

'cors' => \App\Http\Middleware\Cors::class

Finally you must define the middleware to be used, grouping the routes you want to access by the methods you need, either api or web

Route::group(['middleware' => ['api', 'cors'] ...//el resto de tu código 
    
answered by 29.06.2017 / 01:29
source