Laravel 5 Shopping Cart

Download: Laravel Shoppingcart Files

Introduction

Throughout these tutorial series, we have been building an online shopping store. In this tutorial, we are going to implement the shopping cart functionality. We will use a package developed by Crinsane. The package project is on GitHub LaravelShoppingcart

Topics to be covered

We will cover the following topics in this tutorial

  • Installing Laravel Shopping Cart via composer
  • Configuring Laravel 5 to work with Shopping Cart
  • Adding items to the shopping cart
  • Retrieving items from the shopping cart
  • Updating items in the shopping cart
  • Removing items from the shopping cart
  • Clear all items from shopping cart

Installing Laravel Shopping Cart via composer

In this section, we will install the package for Laravel Shopping cart 1. open /composer.json 2. Modify it to the following code

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
		"gloudemans/shoppingcart": "~1.3"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

HERE, - "gloudemans/shoppingcart": "~1.3" installs version 1.3 of the shoppingcart into our Larashop tutorial project

We will now update our composer installation

  1. Open the command prompt
  2. Run the following command to browser to the project root directory
cd C:\xampp\htdocs\larashop

Run the following composer command to install the shopping cart


composer update

You will get the following message when the installation is completed

Use composer here

Configuring Laravel 5 to work with Shopping Cart

We now need to make a few configurations to our project so that the shopping cart can work

  1. open /config/app.php
  2. add the following line to providers array
Gloudemans\Shoppingcart\ShoppingcartServiceProvider::class,

HERE,

  • The above code registers the service provider for the shopping cart.

We will now add an alias name for our shopping cart

  1. open /config/app.php
  2. add the following line to aliases
'Cart'    => Gloudemans\Shoppingcart\Facades\Cart::class,

HERE,

  • The above code defines an alias name that we will be using when working with the shopping cart.

Adding items to the shopping cart

In this section, we are going to implement the shopping cart functionality for the products page only. We will not implement the cart functionality on the home page. This is a tutorial challenge for you to implement.

  1. create HTTP POST verb route that adds items to the cart
  2. modify /resources/views/products.blade.php to include a post method form that submits data with the product id
  3. modify Front controller’s cart method to detect POST form data and add it to the cart

Step 1: HTTP POST verb route

  1. open /app/Http/routes.php
  2. Add the following route
Route::post('/cart', 'Front@cart');

HERE,

  • Route::post('/cart', 'Front@cart'); defines a route for the POST HTTP verb for the URL cart. This route will be used to add items to the shopping cart

Step 2: Products.blade.php FORM

We will now add a form to the products blade template. The form will submit the product id to be added to the cart.

  1. open /resources/views/products.blade.php
  2. modify the contents to the following
@extends('layouts.layout')

@section('content')       
<section id="advertisement">
    <div class="container">
        <img src="{{asset('images/shop/advertisement.jpg')}}" alt="" />
    </div>
</section>

<section>
    <div class="container">
        <div class="row">
            <div class="col-sm-3">
                <div class="left-sidebar">
                    @include('shared.sidebar')
                </div>
            </div>

            <div class="col-sm-9 padding-right">
                <div class="features_items"><!--features_items-->
                    <h2 class="title text-center">Features Items</h2>
                    @foreach ($products as $product)
                    <div class="col-sm-4">
                        <div class="product-image-wrapper">
                            <div class="single-products">
                                <div class="productinfo text-center">
                                    <img src="{{asset('images/shop/product9.jpg')}}" alt="" />
                                    <h2>${{$product->price}}</h2>
                                    <p>{{$product->name}}</p>
                                    <a href="{{url('cart')}}" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                                    <a href='{{url("products/details/$product->id")}}' class="btn btn-default add-to-cart"><i class="fa fa-info"></i>View Details</a>
                                </div>
                                <div class="product-overlay">
                                    <div class="overlay-content">
                                        <h2>${{$product->price}}</h2>
                                        <p>${{$product->name}}</p>
                                        <form method="POST" action="{{url('cart')}}">
                                            <input type="hidden" name="product_id" value="{{$product->id}}">
                                            <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                            <button type="submit" class="btn btn-fefault add-to-cart">
                                                <i class="fa fa-shopping-cart"></i>
                                                Add to cart
                                            </button>
                                        </form>
                                        <a href='{{url("products/details/$product->id")}}' class="btn btn-default add-to-cart"><i class="fa fa-info"></i>View Details</a>
                                    </div>
                                </div>
                            </div>
                            <div class="choose">
                                <ul class="nav nav-pills nav-justified">
                                    <li><a href=""><i class="fa fa-plus-square"></i>Add to wishlist</a></li>
                                    <li><a href=""><i class="fa fa-plus-square"></i>Add to compare</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    @endforeach
                    <ul class="pagination">
                        <li class="active"><a href="">1</a></li>
                        <li><a href="">2</a></li>
                        <li><a href="">3</a></li>
                        <li><a href="">»</a></li>
                    </ul>
                </div><!--features_items-->
            </div>
        </div>
    </div>
</section>
@endsection

HERE,

  • <form method="POST" action="{{url('cart')}}"> creates a HTML form with a POST method. The form data is submitted to /cart URL
  • <input type="hidden" name="product_id" value="{{$product->id}}"> defines a hidden element that contains the product id to be added to the shopping cart.
  • <input type="hidden" name="token" value="{{ csrftoken() }}"> defines a hidden element that contains a security token. The csrf_token() helper function is used to generate the token value.
  • <button type="submit" class="btn btn-fefault add-to-cart"> adds a submission button to our form.

Save the changes

Load the following URL in your web browser

http://localhost/larashop/public/products

Hover over any product.

You will get the following product overlay layer

Use composer here

Add to cart is the submit button

Step 3: Modify Front controller cart method

Before we modify the cart method, we will first need to import the Cart namespace

  1. open /app/Http/Controllers/Front.php
  2. add the following code to import the Request, Redirect and Cart namespaces
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redirect;
use Cart;

HERE,

  • Request is used to access HTTP verbs data
  • Redirect is used to redirect after performing an action that does not need to display anything
  • Cart is used to hold the items in the shopping cart

Locate the method named cart

Update it to the following code

public function cart() {
    if (Request::isMethod('post')) {
        $product_id = Request::get('product_id');
        $product = Product::find($product_id);
        Cart::add(array('id' => $product_id, 'name' => $product->name, 'qty' => 1, 'price' => $product->price));
    }

    $cart = Cart::content();

    return view('cart', array('cart' => $cart, 'title' => 'Welcome', 'description' => '', 'page' => 'home'));
}

HERE,

  • if (Request::isMethod('post')) {…} checks if the request uses the POST HTTP verb. If yes then the code within the if statement block is executed
  • $productid = Request::get('productid'); This code is used to retrieve the value of productid and assigns it to the variable $productid. The get method of Request is used to retrieve variables. get is HTTP agnostic, it can be used to get values for GET as well as POST.
  • $product = Product::find($product_id); uses the product model to retrieve the product from the database. The returned product object is used to get the product name and price.
  • Cart::add(array('id' => $product_id, 'name' => $product->name, 'qty' => 1, 'price' => $product->price)); calls the add method of the Cart and pass in an array of variables. We are passing in the id, name, quantity (qty) and the price. The product name and price are retrieved from the database record.
  • $cart = Cart::content(); calls the content method of Cart to return a collection of items in the shopping cart
  • return view('cart', array('cart' => $cart, 'title' => 'Welcome', 'description' => '', 'page' => 'home')); adds the collection returned from Cart::content() to the list of variables that are passed to the view.

Retrieving items from the shopping cart

We are almost there. Before we can test our shopping cart, we need to modify the contents of cart.blade.php. We want our view to display the contents of the $cart variable.

  1. Open /resources/views/cart.blade.php
  2. Modify the contents to the following
@extends('layouts.layout')

@section('content')       
<section id="cart_items">
    <div class="container">
        <div class="breadcrumbs">
            <ol class="breadcrumb">
                <li><a href="#">Home</a></li>
                <li class="active">Shopping Cart</li>
            </ol>
        </div>
        <div class="table-responsive cart_info">
            @if(count($cart))
            <table class="table table-condensed">
                <thead>
                    <tr class="cart_menu">
                        <td class="image">Item</td>
                        <td class="description"></td>
                        <td class="price">Price</td>
                        <td class="quantity">Quantity</td>
                        <td class="total">Total</td>
                        <td></td>
                    </tr>
                </thead>
                <tbody>
                    @foreach($cart as $item)
                    <tr>
                        <td class="cart_product">
                            <a href=""><img src="images/cart/one.png" alt=""></a>
                        </td>
                        <td class="cart_description">
                            <h4><a href="">{{$item->name}}</a></h4>
                            <p>Web ID: {{$item->id}}</p>
                        </td>
                        <td class="cart_price">
                            <p>${{$item->price}}</p>
                        </td>
                        <td class="cart_quantity">
                            <div class="cart_quantity_button">
                                <a class="cart_quantity_up" href=""> + </a>
                                <input class="cart_quantity_input" type="text" name="quantity" value="{{$item->qty}}" autocomplete="off" size="2">
                                <a class="cart_quantity_down" href=""> - </a>
                            </div>
                        </td>
                        <td class="cart_total">
                            <p class="cart_total_price">${{$item->subtotal}}</p>
                        </td>
                        <td class="cart_delete">
                            <a class="cart_quantity_delete" href=""><i class="fa fa-times"></i></a>
                        </td>
                    </tr>
                    @endforeach
                    @else
                <p>You have no items in the shopping cart</p>
                @endif
                </tbody>
            </table>
        </div>
    </div>
</section> <!--/#cart_items-->

<section id="do_action">
    <div class="container">
        <div class="heading">
            <h3>What would you like to do next?</h3>
            <p>Choose if you have a discount code or reward points you want to use or would like to estimate your delivery cost.</p>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="chose_area">
                    <ul class="user_option">
                        <li>
                            <input type="checkbox">
                            <label>Use Coupon Code</label>
                        </li>
                        <li>
                            <input type="checkbox">
                            <label>Use Gift Voucher</label>
                        </li>
                        <li>
                            <input type="checkbox">
                            <label>Estimate Shipping & Taxes</label>
                        </li>
                    </ul>
                    <ul class="user_info">
                        <li class="single_field">
                            <label>Country:</label>
                            <select>
                                <option>United States</option>
                                <option>Bangladesh</option>
                                <option>UK</option>
                                <option>India</option>
                                <option>Pakistan</option>
                                <option>Ucrane</option>
                                <option>Canada</option>
                                <option>Dubai</option>
                            </select>

                        </li>
                        <li class="single_field">
                            <label>Region / State:</label>
                            <select>
                                <option>Select</option>
                                <option>Dhaka</option>
                                <option>London</option>
                                <option>Dillih</option>
                                <option>Lahore</option>
                                <option>Alaska</option>
                                <option>Canada</option>
                                <option>Dubai</option>
                            </select>

                        </li>
                        <li class="single_field zip-field">
                            <label>Zip Code:</label>
                            <input type="text">
                        </li>
                    </ul>
                    <a class="btn btn-default update" href="">Get Quotes</a>
                    <a class="btn btn-default check_out" href="">Continue</a>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="total_area">
                    <ul>
                        <li>Cart Sub Total <span>$59</span></li>
                        <li>Eco Tax <span>$2</span></li>
                        <li>Shipping Cost <span>Free</span></li>
                        <li>Total <span>${{Cart::total()}}</span></li>
                    </ul>
                    <a class="btn btn-default update" href="{{url('clear-cart')}}">Clear Cart</a>
                    <a class="btn btn-default check_out" href="{{url('checkout')}}">Check Out</a>
                </div>
            </div>
        </div>
    </div>
</section><!--/#do_action-->
@endsection

HERE,

  • @if(count($cart)) line 13 uses the count function to determine if the $cart variable has any contents. If the cart has items, then we dynamically create a table that displays the items
  • @foreach($cart as $item) line 26 uses the foreach loop to loop through the items collection
  • {{$item->name}} displays the product name
  • {{$item->id}} displays the product id
  • {{$item->price}} displays the product price
  • {{$item->subtotal}} displays the product subtotal. The subtotal is the product of quantity and price.
  • {{Cart::total()}} displays the sum total of all items in the shopping cart

Open the following URL in your web browser

http://localhost/larashop/public/products

Hover over a product and click on Add to cart

You will get the following result

Use composer here

Updating items in the shopping cart

For the sake of simplicity, we will use URL query strings to implement the functionality that increments or decrease the quantity when a user click on either the + or – button on the sides of the quantity text box

Locate the following lines in /resources/views/cart.blade.php

<a class="cart_quantity_up" href=""> + </a>
<a class="cart_quantity_down" href=""> - </a>

Update them to the following

<a class="cart_quantity_up" href='{{url("cart?product_id=$item->id&increment=1")}}'> + </a>
<a class="cart_quantity_down" href='{{url("cart?product_id=$item->id&decrease=1")}}'> - </a>

HERE,

  • {{url("cart?productid=$item->id&increment=1")}} generates the URL http://localhost/larashop/public/cart?productid=1&increment=1 . The URL specifies the product id that we want to increment. increment=1 will be used to increment the quantity by 1.
  • {{url("cart?productid=$item->id&increment=0")}} generates the URL http://localhost/larashop/public/cart?productid=1&increment=0. increment=0 will be used to reduce the quantity by 1.

We now need to update the Front controller and add the logic that increments or decreases the quantity.

  1. open /app/Http/Controllers/Front.php
  2. Locate the method cart and modify it to the following
public function cart() {
    //update/ add new item to cart
    if (Request::isMethod('post')) {
        $product_id = Request::get('product_id');
        $product = Product::find($product_id);
        Cart::add(array('id' => $product_id, 'name' => $product->name, 'qty' => 1, 'price' => $product->price));
    }

    //increment the quantity
    if (Request::get('product_id') && (Request::get('increment')) == 1) {
        $rowId = Cart::search(array('id' => Request::get('product_id')));
        $item = Cart::get($rowId[0]);

        Cart::update($rowId[0], $item->qty + 1);
    }

    //decrease the quantity
    if (Request::get('product_id') && (Request::get('decrease')) == 1) {
        $rowId = Cart::search(array('id' => Request::get('product_id')));
        $item = Cart::get($rowId[0]);

        Cart::update($rowId[0], $item->qty - 1);
    }

    $cart = Cart::content();

    return view('cart', array('cart' => $cart, 'title' => 'Welcome', 'description' => '', 'page' => 'home'));
}

HERE,

  • if (Request::get('productid') && (Request::get('increment')) == 1) checks if the productid and increment variables have been set. The condition (Request::get('increment')) == 1 is used to determine the action to be perform. In this instance, we increment the quantity
  • $rowId = Cart::search(array('id' => Request::get('product_id'))); searches through the collection of items using the product id and returns an array of rowIds that match the search criteria. The rowId is a unique identify of an item in the Cart and it is auto generated. It is used to update items in the Cart collection
  • $item = Cart::get($rowId[0]); the get method is used to retrieve an object of an item based on the rowId. $rowId[0] returns the first element in the array. In our case, we only have one item. We are retrieving the item from the collection so that we can know the existing quantity and increment or decrease it.
  • Cart::update($rowId[0], $item->qty + 1); calls the update method of Cart. We are incrementing the quantity by one based on the rowId
  • if (Request::get('productid') && (Request::get('decrease')) == 1) checks if the productid and decrease variables have been set.
  • Cart::update($rowId[0], $item->qty 1); decreases the quantity by

Load the following URL in your web browser

Removing items from the shopping cart

This section shows you how to remove an item from the Cart collection

$rowId = Cart::search(array('id' => Request::get('product_id')));
Cart::remove($rowId[0]);

HERE,

  • Cart::remove($rowId[0]); removes an item from the cart collection based on the supplied rowId

Clear all items from shopping cart

The following code clears all the items from the Cart collection

Cart::destroy();

Summary

In this tutorial, we partially implemented the features of the shopping cart. The goal was to show you how to install Laravel Shoppingcart into your Laravel powered web application and how you can use it to implement a shopping cart. Take it as a challenge to implement the cart in areas that have not been implemented.

What’s next?

The next tutorial will show you how to authenticate users in Laravel 5. If you found these tutorials useful, you can thank us with a tweet, Google plus share and +1, Facebook share and like, and a LinkedIn share and like. If we get enough social media shares, we will fully implement the Larashop, add the admin panel and post the project on Github for a cost of social sharing only.

Tutorial History

Tutorial version 1: Date Published 2015-08-26

Related Tutorials