Laravel E-Commerce Application Development – Shopping Cart

Laravel E-Commerce Application Development – Shopping Cart

Laravel E-Commerce Application Development ( 27 Lessons )

In this course, you’ll learn how to create an E-Commerce Website from scratch in Laravel. The process has never been easier I’ll take you from the very beginning stages of setting up Laravel till the last steps of adding products to the cart. If you’ve good understanding & experience in PHP & MySQL then this course is for you.

see full series
  1. Laravel E-Commerce Application Development – Introduction
  2. Laravel E-Commerce Application Development – Initial Project Setup
  3. Laravel E-Commerce Application Development – Assets Setup Using Laravel Mix
  4. Laravel E-Commerce Application Development – Admin Model and Migration
  5. Laravel E-Commerce Application Development – Backend Admin Authentication
  6. Laravel E-Commerce Application Development – Base Controller and Repository
  7. Laravel E-Commerce Application Development – Settings Section Part 1
  8. Laravel E-Commerce Application Development – Settings Section Part 2
  9. Laravel E-Commerce Application Development – Categories Section Part 1
  10. Laravel E-Commerce Application Development – Categories Section Part 2
  11. Laravel E-Commerce Application Development – Attributes Section Part 1
  12. Laravel E-Commerce Application Development – Attributes Section Part 2
  13. Laravel E-Commerce Application Development – Attributes Section Part 3
  14. Laravel E-Commerce Application Development – Brands Section
  15. Laravel E-Commerce Application Development – Products Section Part 1
  16. Laravel E-Commerce Application Development – Products Section Part 2
  17. Laravel E-Commerce Application Development – Products Section Part 3
  18. Laravel E-Commerce Application Development – Products Section Part 4
  19. Laravel E-Commerce Application Development – Frontend Login & Registration
  20. Laravel E-Commerce Application Development – Categories Navigation
  21. Laravel E-Commerce Application Development – Catalog Listing
  22. Laravel E-Commerce Application Development – Product Details Page
  23. Laravel E-Commerce Application Development – Shopping Cart
  24. Laravel E-Commerce Application Development – Checkout
  25. Laravel E-Commerce Application Development – Payment Processing
  26. Laravel E-Commerce Application Development – Order Management
  27. Laravel E-Commerce Application Development – Wrap Up

This is part 22 of the Laravel E-Commerce Application Development series. In this part, we will start implementing the shopping cart functionality in our application.

I assume you should have the e-commerce application project on your machine or you can grab it from Laravel E-Commerce Application repository, we will start from where we left it in the last part.

Let’s start implementing the shopping cart.

Installing Shopping Cart Package

To add the shopping cart functionality in our application, I will be using the darryldecode/laravelshoppingcart package. This package provides almost everything to handle a shopping cart. Please read more about this package on the repository page.

This package supports the session and database for the purpose of storing shopping cart data. I will be using the session and will not be storing data in the database.

To install this package open the command line terminal and run the below command.

composer require "darryldecode/cart:~4.0"

After installing this package, open the config/app.php file and add below in the aliases array.

'Cart' => Darryldecode\Cart\Facades\CartFacade::class

That’s all, we ready to use the shopping cart functionality using this package.

Adding Shopping Cart Count in Header

If you have noticed we have a link to cart (not functional) in the header section of our website which shows the current count of the cart.

To show the total number of items in the shopping cart, we will use the view composers. Open the ViewComposerServiceProvider from app/Providers folder and add the below code in the boot() method.

View::composer('site.partials.header', function ($view) {
    $view->with('cartCount', Cart::getContent()->count());

In above code example, we are sending a $cartCount variable to our header.blade.php file which contains the current shopping cart count.

Also inlcude the Cart facade in this class like below.

use Cart;

Now, open the resources/views/site/partials/header.blade.php file and update the shopping cart counter to below.

<div class="widget-header">
    <a href="#" class="icontext">
        <div class="icon-wrap icon-xs bg2 round text-secondary"><i
                class="fa fa-shopping-cart"></i></div>
        <div class="text-wrap">
            <small>{{ $cartCount }} items</small>

After finishing this tutorial, don’t forget to add the route('checkout.cart) route to above template.

Updating addToCart Method in Product Controller

Next, we will update the add to cart method in our Product Controller. Open the Product Controller file and replace the addToCart() method with the below one.

public function addToCart(Request $request)
    $product = $this->productRepository->findProductById($request->input('productId'));
    $options = $request->except('_token', 'productId', 'price', 'qty');

    Cart::add(uniqid(), $product->name, $request->input('price'), $request->input('qty'), $options);

    return redirect()->back()->with('message', 'Item added to cart successfully.');

As we know in the last post, we have passed on the following data when adding a product to cart.

  • productId
  • qty
  • price
  • and option like color or size

In the above method, we have to find the product which we need to add to the cart. Then we have removed everything from the $request except color, size or any other attributes and assigned to the $option variable.

Next, we are adding the information to our shopping cart using the Cart::add() method.


See how I am passing a unique shopping cart row id using the uniqid() method. For every row you have to pass the unique id otherwise it will be overwritten.

Finally, we are sending the user back to the product page with a success message.

Try Yourself

By now, you can go back to your application and try to add the product to cart, for confirmation you will see the cart count will change in the header.

Creating Cart Controller

To handle the shopping cart I will create a new controller named CartController. Open the command line terminal and run the below command.

php artisan make:controller Site\CartController

Open the CartController and add the below method in it.

namespace App\Http\Controllers\Site;

use Cart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CartController extends Controller
    public function getCart()
        return view('site.pages.cart');

Now, we will add a few routes to handle our shopping cart.

Route::get('/cart', 'Site\CartController@getCart')->name('checkout.cart');
Route::get('/cart/item/{id}/remove', 'Site\CartController@removeItem')->name('checkout.cart.remove');
Route::get('/cart/clear', 'Site\CartController@clearCart')->name('checkout.cart.clear');

Creating Shopping Cart Page

In this section, we will create a new view named cart. Create a new file in the resources/views/site/pages folder and name it cart.blade.php.

Open this view file and add the below markup in it.

@section('title', 'Shopping Cart')
    <section class="section-pagetop bg-dark">
        <div class="container clearfix">
            <h2 class="title-page">Cart</h2>
    <section class="section-content bg padding-y border-top">
        <div class="container">
            <div class="row">
                <div class="col-sm-12">
                    @if (Session::has('message'))
                        <p class="alert alert-success">{{ Session::get('message') }}</p>
            <div class="row">
                <main class="col-sm-9">
                    @if (\Cart::isEmpty())
                        <p class="alert alert-warning">Your shopping cart is empty.</p>
                        <div class="card">
                            <table class="table table-hover shopping-cart-wrap">
                                <thead class="text-muted">
                                    <th scope="col">Product</th>
                                    <th scope="col" width="120">Quantity</th>
                                    <th scope="col" width="120">Price</th>
                                    <th scope="col" class="text-right" width="200">Action</th>
                                @foreach(\Cart::getContent() as $item)
                                            <figure class="media">
                                                <figcaption class="media-body">
                                                    <h6 class="title text-truncate">{{ Str::words($item->name,20) }}</h6>
                                                    @foreach($item->attributes as $key  => $value)
                                                        <dl class="dlist-inline small">
                                                            <dt>{{ ucwords($key) }}: </dt>
                                                            <dd>{{ ucwords($value) }}</dd>
                                            <var class="price">{{ $item->quantity }}</var>
                                            <div class="price-wrap">
                                                <var class="price">{{ config('settings.currency_symbol'). $item->price }}</var>
                                                <small class="text-muted">each</small>
                                        <td class="text-right">
                                            <a href="{{ route('checkout.cart.remove', $item->id) }}" class="btn btn-outline-danger"><i class="fa fa-times"></i> </a>
                <aside class="col-sm-3">
                    <a href="{{ route('checkout.cart.clear') }}" class="btn btn-danger btn-block mb-4">Clear Cart</a>
                    <p class="alert alert-success">Add USD 5.00 of eligible items to your order to qualify for FREE Shipping. </p>
                    <dl class="dlist-align h4">
                        <dd class="text-right"><strong>{{ config('settings.currency_symbol') }}{{ \Cart::getSubTotal() }}</strong></dd>
                    <figure class="itemside mb-3">
                        <aside class="aside"><img src="{{ asset('frontend/images/icons/pay-visa.png') }}"></aside>
                        <div class="text-wrap small text-muted">
                            Pay 84.78 AED ( Save 14.97 AED ) By using ADCB Cards
                    <figure class="itemside mb-3">
                        <aside class="aside"> <img src="{{ asset('frontend/images/icons/pay-mastercard.png') }}"> </aside>
                        <div class="text-wrap small text-muted">
                            Pay by MasterCard and Save 40%.
                            <br> Lorem ipsum dolor
                    <a href="#" class="btn btn-success btn-lg btn-block">Proceed To Checkout</a>

In this view we are showing the cart table if the shopping cart is not empty using the isEmpty() method. Next, we loading the shopping cart items using the getContent() and running a loop on them and showing the relevant data for this table.

In the Totals section, we are getting the shopping cart total using the getSubTotal() method.

To learn more, please read the shopping cart package’s documentation.

Removing Item from Shopping Cart

To remove an item from the shopping cart we already have a route declared named checkout.cart.remove which points to removeItem() method in the Cart controller.

We will pass the unique id created for each row to this method.

Add the below method in the Cart controller.

public function removeItem($id)

    if (Cart::isEmpty()) {
        return redirect('/');
    return redirect()->back()->with('message', 'Item removed from cart successfully.');

In the above method, we the using the Cart::remove() method to remove the required row.

We are also checking if the cart is empty then sending the user to the homepage.

Clearing Shopping Cart

To clear or destroy the whole shopping cart we will use the Cart::clear() method. Add the below method in the Cart controller.

public function clearCart()

    return redirect('/');

That’s Allllllllllllllll and that’s what we have achieved today.

Shopping Cart Page
Shopping Cart Page

Now, head over to your website and try to add some products in the shopping cart, then delete some from the shopping cart and then try to clear the shopping cart. Everything should work as expected.

What’s Next

In the next post, we will start working on the checkout process where a registered customer can place an order.

Code Repository

You can find the code base of this series on Laravel eCommerce Application repository.

If you have any question about this post, please leave a comment in the comment box below.

Your little help will keep this site alive and help us to produce quality content for you.