Delete record with laravel and ajax

1

The Error that throws me ** *** Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message *

** The data if you identify them but I think the error is in the ajax **

THIS IS MY FORM

{{Form::open(array( 'url'=>'#','id'=>'formulario','method'=>'post'))}}


                    <h1>Eliminar<span class="badge badge-secondary">Productos</span></h1>


                    <div class="form-group">
                        {!! Form::label('id', 'Id:', ['class' => 'col-lg-2 control-label']) !!}
                        <div class="col-lg-10">
                            {!! Form::text('id',$product->id, ['readonly'=>'true'], $value = null, ['class' => 'form-control', 'placeholder' => '']) !!}
                        </div>
                    </div>
                    <br>
                    <br>
                    <div class="form-group">
                        {!! Form::label('producto', 'Producto:', ['class' => 'col-lg-2 control-label']) !!}
                        <div class="col-lg-10">
                            {!! Form::text('producto',$product->producto, ['readonly'=>'true'],  $value = null, ['class' => 'form-control', 'placeholder' => 'Nombre del Producto']) !!}
                        </div>
                    </div>
                    <br>
                    <br>
                    <div class="form-group">
                        {!! Form::label('marca', 'Marca:', ['class' => 'col-lg-2 control-label']) !!}
                        <div class="col-lg-10">
                            {!! Form::text('marca',$product->marca, ['readonly'=>'true'],  $value = null, ['class' => 'form-control', 'placeholder' => 'Marca Del Producto']) !!}
                        </div>
                    </div>
                    <br>
                    <br>

                    <div class="form-group">
                        {!! Form::label('precio', 'Precio:', ['class' => 'col-lg-2 control-label']) !!}
                        <div class="col-lg-10">
                            {!! Form::text('precio',$product->precio, ['readonly'=>'true'],  $value = null, ['class' => 'form-control', 'placeholder' => 'Precio del Producto']) !!}
                        </div>
                    </div>

                    <br>
                    <br>
                    <div class="form-group">
                        {!! Form::label('cantidad', 'Cantidad:', ['class' => 'col-lg-2 control-label']) !!}
                        <div class="col-lg-10">
                            {!! Form::text('cantidad',$product->cantidad, ['readonly'=>'true'],  $value = null, ['class' => 'form-control', 'placeholder' => 'Cantidad del Producto']) !!}
                        </div>
                    </div>
                    <br>
                    <br>
                    <div class="form-group">
                        {!! Form::label('descripcion', 'Descripcion:', ['class' => 'col-lg-2 control-label']) !!}
                        <div class="col-lg-10">
                            {!! Form::textarea('descripcion',$product->comentario, ['readonly'=>'true'],  $value = null, ['class' => 'form-control','maxlength'=>'150', 'placeholder' => 'Descripcion del Producto']) !!}
                        </div>
                    </div>


                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    <div class="modal-footer d-flex justify-content-center">
                        <span class="btn btn-danger" onclick="submit()" id="enviar">Enviar</span>
                    </div>

                    {{Form::close()}}

THIS IS MY AJAX

<script>
function submit() {
    $.ajaxSetup({
        header: $('meta[name="_token"]').attr('content')
    });

    $('#enviar');
    var url = 'productoeliminar2';
    $.ajax({
        type: "POST",
        url: url,
        data: $('#formulario').serialize(),
        dataType: 'html',
        success: function (data) {
            var obj = jQuery.parseJSON(data);
            if ((obj.estado == 'ok')) {
                alert(obj.mensaje);
                window.location = "{{ route('producto') }}"
            } else {
                alert(obj.mensaje);
                $('#enviar').removeAttr("disabled");
            }
        }
    });

}

** my route **

Route::post('productoeliminar2',[
'as'=>'productoeliminar2',
'uses'=>'inventario@productoeli2'

]);

** And this is my function that eliminates **

public static function productoeli2(Request $request){
    \DB::beginTransaction();
    try{
        productos::where('id','=',$request->id)->delete();
        \DB::commit();
        return response()->json(['mensaje'=>'transaccion guardada','estado'=>'ok'],200);

    } catch (\Exception $e) {
        \DB::rollback();
        return response()->json(['mensaje'=>$e->getMessage(),'estado'=>'error'],200);
    }
    
asked by user9472850 14.12.2018 в 04:54
source

1 answer

0

1.- Verify that your route is being detected by Laravel:

php artisan route:list

2.- If it does not appear it may be because it is probably not well defined, if your controller is called inventory from there comes the error) your route should look something like this:

Route::post('productoeliminar2','InventarioController@productoeli2') -> name('productoeliminar2'); 
/* Se puede notar que el nombre del controllador cambió */

3.- Manage the error in Ajax:

 $.ajax({
    ....
    success: function (data) {
        ....
    },
    error: function (data){
       console.log(data);
    }
});

4.-Laravel's good practices indicate that the models should start with capital letters and be handled in the singular, in your case it should be:

Producto::where('id','=',$request->id)->delete();

I would leave your code as follows:

$prod = Producto::find($request->id);
$prod->delete();

I hope you can resolve your doubt.

    
answered by 14.12.2018 в 16:46