Search code examples
ajaxlaravelmodal-dialoge-commercecart

Laravel add to cart button with same product into cart with +1 quantity


I am new to Laravel. Add to cart button to add same product into cart with +1 quantity. Trying to check if stock greater than qty. When one item is qty 3 than 2 stock I would like to display some text "The requested qty is not available" instead of form submit. Is this possible?

Total Stock have 2.

The problem is that more add to cart to same product into +1 quantity. Nothing prevent add to cart “The requested qty is not available”. can anyone help me please.

In Controller

    public function add_to_cart(Request $request)
        {
            $name = $request->product_name;
            $price = $request->product_price;
            $itemno = $request->product_itemno;
            $qty = $request->product_quantity;
            $color = $request->product_color;
            $size = $request->product_size;
    
            $stock = products::join('stocks', 'stocks.pid', 'products.id')
            ->join('sizes', 'sizes.pid', 'products.id')
            ->where([['products.item_no', '=', $itemno],['sizes.size_name', '=', $size]])
            ->first();

            // Current stock quantity
            $stockqty = $stock->qty;
            if($qty <= $stockqty)
            {
             echo "<p>was successfully added to your shopping cart</p>";
    
             Cart::add([
                'id' => $itemno,
                'weight' => 500,
                'name' => $name, 
                'price' => $price, 
                'qty' => $qty, 
                'color' => $color, 
                'size' => $size
                ]);
            }
            else
            {
             echo "<p>The Requested quantity for this product is not available.</p>";
            }
            
        }

In Ajax

$(document).ready(function()
{

$(document).on('click','#add_to_cart',function (e) {
    
        var cart_count = $('.navbar-tool-badge').text();
    cart_count = parseInt(cart_count);
    
    if($('input[type=radio][name=size]:checked').length == 0)
      {
         $('.msg').html('Please choose size.');
         return false;
      } else {
    var product_name = $('#hidden-name').val();
  var product_price = $('#hidden-price').val();
  var product_itemno = $('#itemno').val();
  var product_quantity = $('.quantity').val(); 
  var product_color = $('#color').val();
  var product_size = $("input[name='size']:checked").val();
  
e.preventDefault();
 
$.ajax
({
method:"POST",
url: "{{ route('add_to_cart')}}",
 data:{
  "_token": "{{ csrf_token() }}",
   product_name:product_name,
    product_price:product_price,
     product_itemno:product_itemno,
      product_quantity:product_quantity,
       product_color:product_color,
        product_size:product_size},
cache: false,
success: function(response)
{
$("#getCode").html(response);
$("#myModal").modal('show');

} 
});
}
 });
 
 
});

Solution

  • You can put the value for each product quantity added to cart in the session, whenever add_to_cart is executed. Something like below should work.

    public function add_to_cart(Request $request)
    {
        //You should get only the id of the product and cart from the frontend
        //via ajax request
        //Then you should fetch the Product record from database for that id
        $product = Product::findOrFail($request->pid);
        $cart = Cart::findOrFail($request->cid);
        $sessionKey = "Cart-{$cart->id}-{$product->id}";
        $session = $request->session();
        $requestedQty = $request->product_quantity;
        $desiredQty = 0;
         
        //Get the stock data
        $stock = products::join('stocks', 'stocks.pid', 'products.id')
            ->join('sizes', 'sizes.pid', 'products.id')
            ->where([
                ['products.item_no', '=', $itemno],
                ['sizes.size_name', '=', $size]
            ])
            ->first();
        
        // Current stock quantity
        $stockqty = $stock->qty;
    
        //If the requested quantity is greater than the available stock
        //when the product is added for the first time, send out of stock    
        if($requestedQty > $stockqty) {
            echo "<p>The Requested quantity for this product is not available.</p>";
        }
    
        //When a product is added for the first time session won't have entry
        if(empty($session->get($sessionKey)){ 
            $desiredQty = $requestedQty;       
            $session->put($sessionKey, $requestedQuantity);
        } else {
            $desiredQty = $session->get($sessionKey) + $requestedQty;
        }
    
        if($desiredQty > $stockqty) {
            echo "<p>The Requested quantity for this product is not available.</p>";
        }
    
        //Overwrite the session entry with the new quantity
        $session->put($sessionKey, $desiredQty);
       
        echo "<p>was successfully added to your shopping cart</p>";
        
        Cart::add([
            'id' => $itemno,
            'weight' => 500,
            'name' => $name, 
            'price' => $price, 
            'qty' => $requestedQty, 
            'color' => $color, 
            'size' => $size
        ]);
                
    }