Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

286
Vistas
Laravel : Update Database using Ajax

I have build a shopping cart..Where I tried to update database using ajax..when I will update the quantity, it will reflect the database immediately..

for that i used the following View:

 @foreach($carts as $row)
 <input type="hidden" class="cat_id" value="{{$row->id}}"/>
<input type="number" class="quantity" value="{{$row->no_of_items}}" name="qty" maxlength="3" max="999" min="1" /> &times;${{$row->p_price}}
 @endforeach

Here is the Ajax Part:

$(".quantity").change(updateCart);

    function updateCart(){
        var qty = parseInt($(this).val());
        var cat_id = parseInt($('.cat_id').val());
        console.log(cat_id);

        $.ajaxSetup({
                                headers: {
                              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                             });

          $.ajax({  
                            url:"{{url('cart/update/{cat_id}/{qty}')}}",  
                            method:"POST",  
                            data:{cat_id:cat_id, qty:qty},                              
                               success: function( data ) {
                         // console.log(data);
                        }
                       });
    } 

Route

Route::post('cart/update/{cat_id}/{qty}','ProductController@cartUpdate');

And the controller part :

public function cartUpdate($cat_id, $qty)
    {
        $cart = Cart::find($cat_id);
        $product = Product::find($cart->product_id);
        $cart->no_of_items = Input::get('qty'); 
        $cart->price = $product->price * $cart->no_of_items;
        $cart->save();
    }
  • I have product_id in carts table The problem I'm facing is whenever i tried to update the Quantity i saw error on console mode:

    ErrorException in ProductController.php Trying to get property of non-object

when i dd() the cat_id i see null value or same for all the curt..what could be the possible? thanks

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

The issue is you are not passing the cat_id and qty via the url and is passed via ajax post request


$.ajax({
    url:"{{url('cart/update/{cat_id}/{qty}')}}",  
    method:"POST",  
    data:{
         cat_id : cat_id,
         qty: qty
    },                              
    success: function( data ) {
        // console.log(data);
    }
});

hence the $cat_id and $qty is null in the Controller, so you need to change the code in your controller as


    public function cartUpdate($cat_id, $qty)
    {
        $cart = Cart::find(Input::get('cat_id'));
        $product = Product::find($cart->product_id);
        $cart->no_of_items = Input::get('qty'); 
        $cart->price = $product->price * $cart->no_of_items;
        $cart->save();
    }

about 4 years ago · Santiago Trujillo Denunciar

0

Try This Way:

@foreach($carts as $row)
 <input type="hidden" class="cat_id" name="cat_id" value="{{$row->id}}"/>
 <!--Add name="cat_id" AS Attribute -->
<input type="number" class="quantity{{$row->id}}" value="{{$row->no_of_items}}" name="qty" maxlength="3" max="999" min="1" /> &times;${{$row->p_price}}
@endforeach

And Ajax Part :

 @foreach($carts as $row)
    $(".quantity{{$row->id}}").change(updateCart);
 @endforeach

 function updateCart(){
    var qty = parseInt($(this).val());
    var cat_id = parseInt($('.cat_id').val());
    console.log(cat_id);

      $.ajax({ 
                        headers: {
                          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        url:'cart/update',  
                        method:"POST",  
                        data:{
                            cat_id:cat_id, 
                            qty:qty
                        },                              
                        success: function( data ) {
                     // console.log(data);
                    }
                   });
} 
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda