Home » Laravel: Increase Quantity If Product Already Exists In Cart

Laravel: Increase Quantity If Product Already Exists In Cart

Last updated on November 29, 2020 by

Hello Coders, Today we will see how to increase quantity if product already exists in cart. So without wasting a second, Let’s jump into it.

Prevent Duplicate Product In Cart In Laravel

  1. In the very first step, we will get the requested product data and get the data from the session.
$product_id = $request->all(); /*@ Generally, We pass only product id using ajax/axios but might vary based on requirement */

$cart = Session::get('cart'); /*@ First time session will be blank so we will add condition to check and increase product quantity according */

  1. But the first-time session will have no data so the first time we will assign a product id and product quantity to a variable and we will pass that variable to the session.
$cart[$product_id]['qty'] = 1;

Session::put('cart', $cart);

  1. If the user increases the quantity or requests the same product to add into the cart then the session will have the product data so at that time we need to check if the session will have data then increase the quantity else assign the quantity to 1.
if(isset($cart[$product_id])):
    $cart[$product_id]['qty'] += 1;
endif;

Session::put('cart', $cart);

  1. Now, Let’s join all the bits and pieces all together and make a addToCart function as below:

ProductController.php

<?php

/**
 * Add product to the cart
 *
 * @return success message
 */
public function addToCart(Request $request){
    
    $product_id = $request->all(); /*@ Generally, We pass only product id using ajax/axios but might vary based on requirement */

	$cart = Session::get('cart'); /*@ First time session will be blank so we will add condition to check and increase product quantity according */

    /*
     * If product already exist into the cart then update QTY of product
     * Othewise add new product into the cart
     */
    if(isset($cart[$product_id])):
		$cart[$product_id]['qty'] += 1;
    else:
        $cart[$product_id]['qty'] = 1;
    endif;

    Session::put('cart', $cart);

    return Response::json(['success' => true, 'cart_items' => count(Session::get('cart')), 'message' => 'Cart updated.']);
}

That’s it for now. We hope this article helped you to learn how to increase quantity if product already exists in cart?

Additionally, read our guide Best Way to Remove Public from URL in Laravel

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

 
 

2 thoughts on “Best Way to Remove Public from URL in Laravel”

Leave a Comment