Crinsane / LaravelShoppingcart

A simple shopping cart implementation for Laravel
MIT License
3.67k stars 1.73k forks source link

Laravel Add to cart with same product into cart with +1 Quantity. #647

Closed adilr8 closed 3 years ago

adilr8 commented 3 years ago

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 1 than 2 stock I would like to display some text "successfully added to the cart"

Storing the quantity in session for each product in the cart. Total Stock have 2. if 3 quantity in session than 2 total stock, prevent add to cart. like display "the requested qty is not availabile".

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>";
            }

        }