Laravel Shopping Cart Tutorial Part 2

1 year 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 Prevent the Loop Incrementing Operator from Resetting Back to 1 in the Next Pagination Pages in Laravel

In this lesson, we will see how to prevent the loop incrementing operator from resetting back to 1 i...


How to Logout a User from the Other Devices in Laravel 11

In this lesson, we will see how to logout a user from the other devices in Laravel 11, sometimes you...


How to Logout a User from the Current Device in Laravel 11

In this lesson, we will see how to logout a user from the current device in Laravel 11, sometimes yo...


How to Import Multiple Classes from a Single Namespace in Laravel

In this lesson, we will see how to import multiple classes from a single namespace in Laravel by add...


Laravel 11 Livewire CRUD Application Tutorial Part 2

In the second part of this tutorial, we will display all the tasks on the home page and later we wil...


Laravel 11 Livewire CRUD Application Tutorial Part 1

This tutorial will show us how to create a Laravel 11 Livewire CRUD application. The user can c...


How to Conditionally Include a Blade Template in Laravel

In this lesson, we will see how to conditionally include a blade template in Laravel.Sometimes,...


How to Include a Blade Template Only if it Exists in Laravel

In this lesson, we will see how to include a blade template only if it exists in Laravel.Sometimes,&...


How to Pass a Variable to Include in Laravel

In this lesson, we will see how to pass a variable to include in Laravel. Sometimes, we want to pass...


How to the Get the Previous and Next Posts in Laravel

In this lesson, we will see how to get the previous and next posts in Laravel, sometimes when you ge...