Laravel Shopping Cart Tutorial Part 2

7 months ago admin Laravel

In the second part of this tutorial, we will see how to add products to the cart, update the product's quantity in the cart, and remove a product from the cart.


Create the controller

Next, we create a new controller 'CartController' Inside we have functions that fetch add updates and remove products from the cart.

                                                        
                                                                                                                        
<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class CartController extends Controller
{
    //
    public function addToCart(Product $product) 
    {
        \Cart::add(array(
            'id' => $product->id,
            'name' => $product->product_name,
            'price' => $product->product_price,
            'quantity' => 1,
            'attributes' => array(),
            'associatedModel' => $product
        ));
        return redirect()->route('cart.index');
    }

    public function cartItems() 
    {
        $items = \Cart::getContent();
        return view('cart')->with([
            'items' => $items
        ]);
    }

    public function incrementQ(Product $product)
    {
        \Cart::update($product->id, array(
            'quantity' => 1, 
        ));
        return redirect()->route('cart.index');
    }

    public function decrementQ(Product $product)
    {
        \Cart::update($product->id, array(
            'quantity' => -1, 
        ));
        return redirect()->route('cart.index');
    }

    public function removeFromCart(Product $product)
    {
        \Cart::remove($product->id);
        return redirect()->route('cart.index');
    }
}


Create the home page

Next, let's update the 'welcome' page and add the code below to fetch and display all the products from the database.

                                                            
                                                                                                                                
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Laravel Shopping Cart</title>
  </head>
  <body>
    <div class="container">
        <div class="row my-5">
            @foreach ($products as $product)
                <div class="col-md-6">
                    <div class="card">
                        <img src="{{$product->product_image}}" height="300" alt="...">
                    </div>
                    <div class="card-body">
                        <h5 class="card-title">{{$product->product_name}}</h5>
                        <p class="card-text">{{$product->product_description}}</p>
                        <h5 class="text-danger">${{$product->product_price}}</h5>
                        <a href="{{route('add.cart', $product)}}" class="btn btn-primary">Add to cart</a>
                    </div>   
                </div>
            @endforeach
        </div>
    </div>
    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>

Fetch and Display products from the cart

Next, to fetch and display products from the cart, let's create a new file inside views 'cart.blade.php' inside we fetch and display all the products from the cart with the total amount to pay, we have also links that update and remove products from the cart.

Demo

                                                            
                                                                                                                                
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

    <title>Laravel Shopping Cart</title>
  </head>
  <body>
    <div class="container">
        <div class="row my-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <div class="my-2">
                            <a href="{{route('home')}}" class="btn-link">
                                Home
                            </a>
                        </div>
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Image</th>
                                    <th>Name</th>
                                    <th>Quantity</th>
                                    <th>Price</th>
                                    <th>Subtotal</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($items as $item)
                                    <tr>
                                        <td>{{$item->id}}</td>
                                        <td>
                                            <img src="{{$item->associatedModel->product_image}}" 
                                                class="fluid rounded"
                                                width="60"
                                                height="60"    
                                                alt="{{$item->name}}" />
                                        </td>
                                        <td>
                                            {{$item->name}}
                                        </td>
                                        <td>
                                            <a href="{{route('quantity.inc', $item->id)}}" class="text-decoration-none text-dark">
                                                <i class="bi bi-caret-up" style="cursor: pointer"></i>
                                            </a>
                                            <span class="mx-2">
                                                {{$item->quantity}}
                                            </span>
                                            <a href="{{route('quantity.dec', $item->id)}}" class="text-decoration-none text-dark">
                                                <i class="bi bi-caret-down" style="cursor: pointer"></i>
                                            </a>
                                        </td>
                                        <td>
                                            {{$item->price}}
                                        </td>
                                        <td>
                                            {{$item->quantity * $item->price}}
                                        </td>
                                        <td>
                                            <a href="{{route('remove.cart', $item->id)}}" class="text-decoration-none text-dark">
                                                <i class="bi bi-cart-x text-danger" style="cursor: pointer"></i>
                                            </a>
                                        </td>
                                    </tr>
                                @endforeach
                                <tr>
                                    <th colSpan="3" class="text-center">
                                        Total
                                    </th>
                                    <td colSpan="3" class="text-center">
                                        <span class="badge bg-danger rounded-pill">
                                            ${{\Cart::getTotal()}}
                                        </span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>

Add routes

Finally, we add the routes we need.

Demo

                                                            
                                                                                                                                
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CartController;
use App\Http\Controllers\ProductController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', [ProductController::class, 'index'])->name('home');
Route::get('add/{product}/cart', [CartController::class, 'addToCart'])->name('add.cart');
Route::get('cart', [CartController::class, 'cartItems'])->name('cart.index');
Route::get('increment/{product}', [CartController::class, 'incrementQ'])->name('quantity.inc');
Route::get('decrement/{product}', [CartController::class, 'decrementQ'])->name('quantity.dec');
Route::get('remove/{product}', [CartController::class, 'removeFromCart'])->name('remove.cart');

Related Tuorials

How to Check if a Record Does Not Exist in Laravel

in this lesson, we will see how to check if a record does not exist in laravel, sometimes you need t...


How to Check if a Record Exists in Laravel

in this lesson, we will see how to check if a record exists in laravel, sometimes you need to check...


How to Decrement Multiple Fields in Laravel

In this lesson, we will see how to decrement multiple fields in Laravel, in the old versions of lara...


How to Increment Multiple Fields in Laravel

In this lesson, we will see how to increment multiple fields in Laravel, in the old versions of lara...


How to Use the Same Request Validation Rules for Storing and Updating in Laravel

In this lesson, we will see how to use the same request validation rules for storing and updating in...


How to Go Back to the Previous URL in Laravel Blade

In this lesson, we will see how to go back to the previous URL in Laravel Blade, sometimes we need t...


How to Add Additional Data to The Resource JSON Response in Laravel

In this lesson, we will see how to add additional data to the resource JSON response in Laravel, let...


How to Specify the Attributes to be Returned in the Laravel Find Method

In this lesson, we will see how to specify the attributes to be returned in the Laravel find method,...


How to Get Data Using Where All in Laravel

In this lesson, we will see how to get data using Where All in Laravel, the Where All method is used...


How to Get Data Using Where Any in Laravel

In this lesson, we will see how to get data using Where Any in Laravel, the Where Any method is used...