Creating a Simple Shopping Cart Application - Step 2 - Adding a Navbar and Cart - *** Bootstrap 5 Version ***

*** This post is identical to the previous version apart from the code for the navbar which has been updated to reflect the changes to the way BS5 handles navbars ***

In this post we will extend the functionality of the shop window with a navbar showing the number of items in the cart and two navbar buttons to empty the cart or proceed to the checkout page.

Edit the file resources/views/products/displaygrid.blade.php and add the following code a the top of the page after the @section('content') but before @include('flash::message')

<div style="padding-top:1%"> 
    <nav class="navbar navbar-right navbar-expand-sm navbar-dark bg-dark">
        <ul class="navbar-nav ms-auto">
            <li class="nav-item"><button id="checkOut" onclick="window.location.href=''" type="button" style="margin-right:5px;" class="btn btn-primary navbar-btn center-block">Check Out</button></li> 
            <li class="nav-item"><button id="emptycart" type="button" style="margin-right:5px;" class="btn btn-primary navbar-btn center-block">Empty Cart</button></li> 
            <li class="nav-item"><span style="font-size:40px;margin-right:0px;" class="glyphicon glyphicon-shopping-cart navbar-btn"></span></li> 
            <li class="nav-item"><div class="navbar-text" id="shoppingcart" style="font-size:12pt;margin-left:5px;margin-right:0px;"></div></li> 
            <li class="nav-item"><div class="navbar-text" style="font-size:14pt;margin-left:0px;">Item(s)</div></li>        
        <ul> 
    </nav> 
</div>

Next, we need to add a function to the controller which will put some items in the cart when called. This function uses the Session class. In order to use this class we need to add the following use statement to the top of the productsController along with the other use statements

use Session;
You can add the following function further down in the productsController.php file along with the other functions.
public function additem($productid)
{
    if (Session::has('cart')) {
        $cart = Session::get('cart');
        if (isset($cart[$productid])) {
            $cart[$productid]=$cart[$productid]+1; //add one to product in cart
        }
        else {
            $cart[$productid]=1; //new product in cart
        }
    }
    else {
        $cart[$productid]=1; //new cart
    }
    Session::put('cart', $cart);
    return Response::json(['success'=>true,'total'=>array_sum($cart)],200);
}

The cart will be stored in a PHP associative array taking the form $productid => $qty. The productid is the index into the array. That element in the array will store the quantity of that product in the cart. This is the stored in the session. The various if statements check is there already a session and if there is - are there already any of those items in the cart?

Normally this function would be called by a $_POST request from a form. In this example we don't have a form. Also having to submit the page and leave the shop window just to add one item to the cart would detract from the user experience. Rather than doing a submit we will do a jquery Asynchronous Javascript And XML function call. This will allow the data to be passed in a $_POST request as if it came from a form but rather than leaving the page the submit will be performed in the background while the user continues to look at the shop window. Ajax can be a little bit confusing if you're not used to it but the modern web is built on this kind of user experience and jquery has done a good job of making it easier to use.

Now we need to add our jquery code which calls the additem action - to do this, add the the following snippet of jquery code inside some script tags at the bottom of the resources/views/products/displaygrid.blade.php page

$(".bth,.addItem").click(function() {
    var total = parseInt($('#shoppingcart').text());
    var i=$(this).val();
    $('#shoppingcart').text(total);    
    $.ajax({
      type: "get",
      url: "{{url('products/additem/')}}" + "/" + i,
      type: "GET",
      success: function(response) {
          total=total+1;
          $('#shoppingcart').text(response.total);
      },
      error: function() {
          alert("problem communicating with the server");
      }
    });
});

If we have an additem( ) function in the controller then we must have a corresponding route. Add the following line to routes/web.php

Route::get('products/additem/{id}', 'App\Http\Controllers\productController@additem')->name('products.additem');

The addItem buttons will now add items to the cart. The quantity of each item which has been added will be stored in the session variable containing the cart and the div container in the navbar indicating the total number of items in the cart will be updated. The sucess function within the jquery call ensures that this will only happen if we get a success response from the server indicating that the item has been added to the cart.

In the next post I'll show you how to make sure the contents of the cart are loaded when the page loads and we'll add a function to empty the cart.

Leave a Reply