Contact US


Get Your Project Done by our experts
info@fundaofwebit.com

How to make shopping cart using cookie in laravel with Ajax

Whatsapp

https://www.fundaofwebit.com/post/how-to-make-shopping-cart-using-cookie-in-laravel-with-ajax-request

How to make shopping cart using Cookie in laravel


Step 1: Let's create a simple design of product with Input box of Quantity and Add to Cart button. Now lets integrate the below code as per our template design.


@section('content')

<div class="container">
    <div class="row product_data">

        <div class="col-md-4">
            <img src="{{ asset('products/image-1.jpg') }}" class="w-100" alt="Product 1">
            <h4>Product 1</h4>
            <input type="hidden" class="product_id" value="1"> <!-- Your Product ID -->
            <input type="text" class="qty-input" value="2"> <!-- Your Number of Quantity -->
            <button type="button" class="add-to-cart-btn btn btn-primary">Add to Cart</button>
        </div>
        <div class="col-md-4">
            <img src="{{ asset('products/image-2.jpg') }}" class="w-100" alt="Product 2">
            <h4>Product 1</h4>
            <input type="hidden" class="product_id" value="2"> <!-- Your Product ID -->
            <input type="text" class="qty-input" value="2"> <!-- Your Number of Quantity -->
            <button type="button" class="add-to-cart-btn btn btn-primary">Add to Cart</button>
        </div>
        <div class="col-md-4">
            <img src="{{ asset('products/image-3.jpg') }}" class="w-100" alt="Product 3">
            <h4>Product 1</h4>
            <input type="hidden" class="product_id" value="3"> <!-- Your Product ID -->
            <input type="text" class="qty-input" value="1"> <!-- Your Number of Quantity -->
            <button type="button" class="add-to-cart-btn btn btn-primary">Add to Cart</button>
        </div>

    </div>
</div>

@endsection


Step 2: Now Lets create a js file named custom.js and paste the below script for adding the product to cart with ajax jquery


    $(document).ready(function () {
        $('.add-to-cart-btn').click(function (e) {
            e.preventDefault();

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

            var product_id = $(this).closest('.product_data').find('.product_id').val();
            var quantity = $(this).closest('.product_data').find('.qty-input').val();

            $.ajax({
                url: "/add-to-cart",
                method: "POST",
                data: {
                    'quantity': quantity,
                    'product_id': product_id,
                },
                success: function (response) {
                    alertify.set('notifier','position','top-right');
                    alertify.success(response.status);
                },
            });
        });
    });


Step 3: Let's move to route/web.php file where we will add the url as follows


    Route::post('add-to-cart','Frontend\CartController@addtocart');

Change your controller name as per your requirement in above route.

Step 4: Now, open our controller file as per the above route mentioned path= App/Http/Controller/Frontend/CartController.php or else create a controller by given below command as follows


    $ php artisan make:controller Frontend/CartController


Step 5: Now, we need to create a Product Model where the products data or details are stored like image, name, price, descrip, etc. So we will be using this Product Model to get the records by product_id as we have mentioned in Step 1 design class as product_id.

Step 6: Now paste the code in our CartController.php file for add to cart functionality


use Illuminate\Support\Facades\Cookie;

    public function addtocart(Request $request)
    {

        $prod_id = $request->input('product_id');
        $quantity = $request->input('quantity');

        if(Cookie::get('shopping_cart'))
        {
            $cookie_data = stripslashes(Cookie::get('shopping_cart'));
            $cart_data = json_decode($cookie_datatrue);
        }
        else
        {
            $cart_data = array();
        }

        $item_id_list = array_column($cart_data'item_id');
        $prod_id_is_there = $prod_id;

        if(in_array($prod_id_is_there$item_id_list))
        {
            foreach($cart_data as $keys => $values)
            {
                if($cart_data[$keys]["item_id"] == $prod_id)
                {
                    $cart_data[$keys]["item_quantity"] = $request->input('quantity');
                    $item_data = json_encode($cart_data);
                    $minutes = 60;
                    Cookie::queue(Cookie::make('shopping_cart'$item_data$minutes));
                    return response()->json(['status'=>'"'.$cart_data[$keys]["item_name"].'" Already Added to Cart','status2'=>'2']);
                }
            }
        }
        else
        {
            $products = Products::find($prod_id);
            $prod_name = $products->name;
            $prod_image = $products->image;
            $priceval = $products->price;

            if($products)
            {
                $item_array = array(
                    'item_id' => $prod_id,
                    'item_name' => $prod_name,
                    'item_quantity' => $quantity,
                    'item_price' => $priceval,
                    'item_image' => $prod_image
                );
                $cart_data[] = $item_array;

                $item_data = json_encode($cart_data);
                $minutes = 60;
                Cookie::queue(Cookie::make('shopping_cart'$item_data$minutes));
                return response()->json(['status'=>'"'.$prod_name.'" Added to Cart']);
            }
        }
    }


Step 7: Now you will be able to see that your product is added into your Cookie cart. Now lets lets count the total number of products added into Cart Cookie and view in a page.

Counting all the data or porducts added into the cart of Cookie 

Step 2.1: First we will count the total number of products added into it, so paste this below into your global js file so you can access everywhere. eg: custom.js into your public dir and add it into your layouts.webpage


    $(document).ready(function () {
        cartload();
    });

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

        $.ajax({
            url: '/load-cart-data',
            method: "GET",
            success: function (response) {
                $('.basket-item-count').html('');
                var parsed = jQuery.parseJSON(response)
                var value = parsed//Single Data Viewing
                $('.basket-item-count').append($('<span class="badge badge-pill red">'value['totalcart'] +'</span>'));
            }
        });
    }


Step 2.2: Lets add a route to count the added products into cart cookie. path: route/web.php


    Route::get('/load-cart-data','Frontend\CartController@cartloadbyajax');


Step 2.3: Goto to your controller App/Http/Controller/Frontend/CartController.php and paste the below code.


use Illuminate\Support\Facades\Cookie;

    public function cartloadbyajax()
    {
        if(Cookie::get('shopping_cart'))
        {
            $cookie_data = stripslashes(Cookie::get('shopping_cart'));
            $cart_data = json_decode($cookie_datatrue);
            $totalcart = count($cart_data);

            echo json_encode(array('totalcart' => $totalcart)); die;
            return;
        }
        else
        {
            $totalcart = "0";
            echo json_encode(array('totalcart' => $totalcart)); die;
            return;
        }
    }


Step 2.4: to view the output which your getting the data from your above CartController.php file of cartloadbyajax function into your blade.php file as per your requirement. (I have done this in Navbar)


<span class="clearfix">
    Cart
    <span class="basket-item-count">
        <span class="badge badge-pill red"> 0 </span>
    </span>
</span>

Now you can see here total of products added  into cart. 

Showing all the products which we have added into cart Cookie

Step 3.1: Lets make a url to view all the products into a page i.e added into cart cookie.


    Route::get('/cart','Frontend\CartController@index');


Step 3.2: go to your controller CartController.php file and paste the below code:


use Illuminate\Support\Facades\Cookie;

    public function index()
    {
        $cookie_data = stripslashes(Cookie::get('shopping_cart'));
        $cart_data = json_decode($cookie_datatrue);
        return view('frontend.cart')
            ->with('cart_data',$cart_data)
        ;
    }


Step 3.3: Now, let's create a page in for cart for viewing the products details path: frontend/cart/index.blade.php

@extends('layouts.frontend')

@section('content')

<section class="bg-success">
    <div class="container">
        <div class="row">
            <div class="col-md-12 mt-2 py-3">
                <h5><a href="/" class="text-dark">Home</a> › Cart</h5>
            </div>
        </div>
    </div>
</section>

<section class="section">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                @if(isset($cart_data))
                    @if(Cookie::get('shopping_cart'))
                        @php $total="0" @endphp
                        <div class="shopping-cart">
                            <div class="shopping-cart-table">
                                <div class="table-responsive">
                                    <div class="col-md-12 text-right mb-3">
                                        <a href="javascript:void(0)" class="clear_cart font-weight-bold">Clear Cart</a>
                                    </div>
                                    <table class="table table-bordered my-auto  text-center">
                                        <thead>
                                            <tr>
                                                <th class="cart-description">Image</th>
                                                <th class="cart-product-name">Product Name</th>
                                                <th class="cart-price">Price</th>
                                                <th class="cart-qty">Quantity</th>
                                                <th class="cart-total">Grandtotal</th>
                                                <th class="cart-romove">Remove</th>
                                            </tr>
                                        </thead>
                                        <tbody class="my-auto">
                                            @foreach ($cart_data as $data)
                                            <tr class="cartpage">
                                                <td class="cart-image">
                                                    <a class="entry-thumbnail" href="javascript:void(0)">
                                                        <img src="{{ asset('admin/uploads/productcatelist/'.$data['item_image']) }}" width="70px" alt="">
                                                    </a>
                                                </td>
                                                <td class="cart-product-name-info">
                                                    <h4 class='cart-product-description'>
                                                        <a href="javascript:void(0)">{{ $data['item_name'}}</a>
                                                    </h4>
                                                </td>
                                                <td class="cart-product-sub-total">
                                                    <span class="cart-sub-total-price">{{ number_format($data['item_price'], 2}}</span>
                                                </td>
                                                <td class="cart-product-quantity">
                                         <input type="number" class="qty-input form-control" value="{{ $data['item_quantity'] }}" min="1" max="100"/>
                                                </td>
                                                <td class="cart-product-grand-total">
                                                    <span class="cart-grand-total-price">{{ number_format($data['item_quantity'] * $data['item_price'], 2}}</span>
                                                </td>
                                                <td style="font-size: 20px;">
                                                    <button type="button" class="delete_cart_data"><li class="fa fa-trash-o"></li> Delete</button>
                                                </td>
                                                @php $total = $total + ($data["item_quantity"] * $data["item_price"]) @endphp
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table><!-- /table -->
                                </div>
                            </div><!-- /.shopping-cart-table -->
                            <div class="row">

                                <div class="col-md-8 col-sm-12 estimate-ship-tax">
                                    <div>
                                        <a href="{{ url('collections') }}" class="btn btn-upper btn-warning outer-left-xs">Continue Shopping</a>
                                    </div>
                                </div><!-- /.estimate-ship-tax -->

                                <div class="col-md-4 col-sm-12 ">
                                    <div class="cart-shopping-total">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6 class="cart-subtotal-name">Subtotal</h6>
                                            </div>
                                            <div class="col-md-6">
                                                <h6 class="cart-subtotal-price">
                                                    Rs.
                                                    <span class="cart-grand-price-viewajax">{{ number_format($total2}}</span>
                                                </h6>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6 class="cart-grand-name">Grand Total</h6>
                                            </div>
                                            <div class="col-md-6">
                                                <h6 class="cart-grand-price">
                                                    Rs.
                                                    <span class="cart-grand-price-viewajax">{{ number_format($total2}}</span>
                                                </h6>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="cart-checkout-btn text-center">
                                                    @if (Auth::user())
                                                        <a href="{{ url('checkout') }}" class="btn btn-success btn-block checkout-btn">PROCCED TO CHECKOUT</a>
                                                    @else
                                                        <a href="{{ url('login') }}" class="btn btn-success btn-block checkout-btn">PROCCED TO CHECKOUT</a>
                                                        {{-- you add a pop modal for making a login --}}
                                                    @endif
                                                    <h6 class="mt-3">Checkout with Fabcart</h6>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div><!-- /.shopping-cart -->
                    @endif
                @else
                    <div class="row">
                        <div class="col-md-12 mycard py-5 text-center">
                            <div class="mycards">
                                <h4>Your cart is currently empty.</h4>
                                <a href="{{ url('collections') }}" class="btn btn-upper btn-primary outer-left-xs mt-5">Continue Shopping</a>
                            </div>
                        </div>
                    </div>
                @endif

            </div>
        </div> <!-- /.row -->
    </div><!-- /.container -->
</section>

@endsection


As We completed have completed with the Cart Page design and fetch the Cookie Cart data, now we have to modify the one thing in above cart page i.e Step 3.3, about Quantity Increment and Decrement using jquery.

Step 4.1: Let's Paste the below code which is done by using Bootstrap v4.5 in our cart page design in Step 3.3 at place of input quantity box as follows:


    <td class="cart-product-quantity" width="130px">
        <div class="input-group quantity">
            <div class="input-group-prepend decrement-btn changeQuantity" style="cursor: pointer">
                <span class="input-group-text">-</span>
            </div>
            <input type="text" class="qty-input form-control" maxlength="2" max="10" value="{{ $data['item_quantity'] }}">
            <div class="input-group-append increment-btn changeQuantity" style="cursor: pointer">
                <span class="input-group-text">+</span>
            </div>
        </div>
    </td>
 


Step 4.2: Now let's paste the below code for functionality which we want to perform like number increment and decrement of the quantity as follows:


    $(document).ready(function () {

        $('.increment-btn').click(function (e) {
            e.preventDefault();
            var incre_value = $(this).parents('.quantity').find('.qty-input').val();
            var value = parseInt(incre_value10);
            value = isNaN(value) ? 0 : value;
            if(value<10){
                value++;
                $(this).parents('.quantity').find('.qty-input').val(value);
            }
        });

        $('.decrement-btn').click(function (e) {
            e.preventDefault();
            var decre_value = $(this).parents('.quantity').find('.qty-input').val();
            var value = parseInt(decre_value10);
            value = isNaN(value) ? 0 : value;
            if(value>1){
                value--;
                $(this).parents('.quantity').find('.qty-input').val(value);
            }
        });

    });


Now let's lets begin Shopping Cart with updating the price when quantity increments or decrements using jquery ajax with Cookie, Now lets start:

Step 5.1: Paste the below script in your custom.js file as follows:

As we are getting the input product_id and input quantity data from Cookie Cart and getting them in script.

include this cart page above quantity tag: <input type="hidden" class="product_id" value="{{ $data['item_id'] }}" >


    // Update Cart Data
    $(document).ready(function () {

        $('.changeQuantity').click(function (e) {
            e.preventDefault();

            var quantity = $(this).closest(".cartpage").find('.qty-input').val();
            var product_id = $(this).closest(".cartpage").find('.product_id').val();

            var data = {
                '_token': $('input[name=_token]').val(),
                'quantity':quantity,
                'product_id':product_id,
            };

            $.ajax({
                url: '/update-to-cart',
                type: 'POST',
                data: data,
                success: function (response) {
                    window.location.reload();
                    alertify.set('notifier','position','top-right');
                    alertify.success(response.status);
                }
            });
        });

    });


Step 5.2: Let's give a url, which will be called when quantity will be incremented or decremented by ajax call: 


    Route::post('update-to-cart','Frontend\CartController@updatetocart');


Step 5.3: Now go to our CartController.php and make a function and paste the below code:


    public function updatetocart(Request $request)
    {
        $prod_id = $request->input('product_id');
        $quantity = $request->input('quantity');

        if(Cookie::get('shopping_cart'))
        {
            $cookie_data = stripslashes(Cookie::get('shopping_cart'));
            $cart_data = json_decode($cookie_datatrue);

            $item_id_list = array_column($cart_data'item_id');
            $prod_id_is_there = $prod_id;

            if(in_array($prod_id_is_there$item_id_list))
            {
                foreach($cart_data as $keys => $values)
                {
                    if($cart_data[$keys]["item_id"] == $prod_id)
                    {
                        $cart_data[$keys]["item_quantity"] =  $quantity;
                        $item_data = json_encode($cart_data);
                        $minutes = 60;
                        Cookie::queue(Cookie::make('shopping_cart'$item_data$minutes));
                        return response()->json(['status'=>'"'.$cart_data[$keys]["item_name"].'" Quantity Updated']);
                    }
                }
            }
        }
    }


Now lets begin with Deleteing the product from Shopping Cart Cookie using jquery:

we will be doing that how to remove or delete the single record from your Cookie in laravel using jquery.

Step 6.1: Paste the below following code for removing data from cookie shopping cart:

Give a class name  as delete_cart_data in your Cart Page and follow: 

include this cart page above quantity tag: <input type="hidden" class="product_id" value="{{ $data['item_id'] }}" >


    // Delete Cart Data
    $(document).ready(function () {

        $('.delete_cart_data').click(function (e) {
            e.preventDefault();

            var product_id = $(this).closest(".cartpage").find('.product_id').val();

            var data = {
                '_token': $('input[name=_token]').val(),
                "product_id": product_id,
            };

            // $(this).closest(".cartpage").remove();

            $.ajax({
                url: '/delete-from-cart',
                type: 'DELETE',
                data: data,
                success: function (response) {
                    window.location.reload();
                }
            });
        });

    });


Step 6.2: Now, Let's set the url for it:


    Route::delete('delete-from-cart','Frontend\CartController@deletefromcart');


Step 6.3: Now go to our CartController.php and make a function and paste the below code:


    public function deletefromcart(Request $request)
    {
        $prod_id = $request->input('product_id');

        $cookie_data = stripslashes(Cookie::get('shopping_cart'));
        $cart_data = json_decode($cookie_datatrue);

        $item_id_list = array_column($cart_data'item_id');
        $prod_id_is_there = $prod_id;

        if(in_array($prod_id_is_there$item_id_list))
        {
            foreach($cart_data as $keys => $values)
            {
                if($cart_data[$keys]["item_id"] == $prod_id)
                {
                    unset($cart_data[$keys]);
                    $item_data = json_encode($cart_data);
                    $minutes = 60;
                    Cookie::queue(Cookie::make('shopping_cart'$item_data$minutes));
                    return response()->json(['status'=>'Item Removed from Cart']);
                }
            }
        }
    }


Finally We reached at last Task about how to clear or delete the Cookie in laravel:

Step 7.1: Lets paste the below code in custom.js file as follows: 


    // Clear Cart Data
    $(document).ready(function () {

        $('.clear_cart').click(function (e) {
            e.preventDefault();

            $.ajax({
                url: '/clear-cart',
                type: 'GET',
                success: function (response) {
                    window.location.reload();
                    alertify.set('notifier','position','top-right');
                    alertify.success(response.status);
                }
            });

        });

    });



Step 7.2: Now, Let's set the url for it:


    Route::get('clear-cart','Frontend\CartController@clearcart');


Step 7.3: Now go to our CartController.php and make a function and paste the below code:


    public function clearcart()
    {
        Cookie::queue(Cookie::forget('shopping_cart'));
        return response()->json(['status'=>'Your Cart is Cleared']);
    }



© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT