Laravel 10 Bootstrap Add Product to Shopping Cart Tutorial

Last Updated on by in Laravel

In this comprehensive tutorial, you will learn how to create an eCommerce shopping cart in the Laravel application. To design a cart in Laravel, we will use the Bootstrap library and the laravel seeder to seed the database with sample records.

A cart functionality is an imperative feature mostly used in eCommerce applications. It allows users to add items to a virtual shopping cart as they browse through a website or an online store.

The items added to the cart can be checked, edited, and eventually checked out to complete the purchase.

To implement a shopping cart in Laravel, you can follow these steps:

How to Create an eCommerce Shopping Cart in Laravel 10

  • Step 1: Download Laravel Project
  • Step 2: Add Database Details
  • Step 3: Create Model and Migrations
  • Step 4: Populate Records in Database
  • Step 5: Build Product Controller
  • Step 6: Create New Routes
  • Step 7: Create Cart View
  • Step 8: Add Products to Cart

Download Laravel Project

To start building a Laravel application, you must have the Laravel framework installed on a web server or your local machine.

Here are the steps to install a Laravel application:

composer create-project laravel/laravel --prefer-dist laravel-blog

Go into the project directory:

cd laravel-blog

Add Database Details

To connect laravel application to the database, add database details in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Model and Migrations

We will create a cart model by the name of Book. This model will represent a cart in our laravel application and should have columns to store the items in the cart.

php artisan make:model Book

Open the app/Models/Book.php file and add the following code in the file.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;
    protected $fillable = [
        'name', 
        'author', 
        'image', 
        'price'
    ];    
}

Create a new migration file; it will create a new table in the database.

php artisan make:migration create_books_table

Add code into the database/migrations/xxx_create_books_table.php file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string("name", 255)->nullable();
            $table->text("author")->nullable();
            $table->string("image", 255)->nullable();
            $table->decimal("price", 6, 2);            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
};

To run migrations, you can take help of the Artisan command line tool.

php artisan migrate

Populate Records in Database

We need to have a couple of data or products in the database. We can populate the sample records in the table, and use command to create a seeder.

php artisan make:seed BookSeeder

You have to insert the suggested code in the app/database/seeders/BookSeeder.php file.

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Book;

class BookSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $books = [
            [
                'name' => 'Slayer',
                'author' => 'Kiersten White',
                'image' => 'https://bookcart.azurewebsites.net/Upload/6d91b7b0-b8d1-41ad-a0ef-65e2324fc1b3Slayer.jpg',
                'price' => 1314
            ],
            [
                'name' => 'The Simple Wild',
                'author' => 'KA Tucker',
                'image' => 'https://bookcart.azurewebsites.net/Upload/b868eb26-f12c-4dcf-ba19-03e0d6cafb8d36373564.jpg',
                'price' => 1153
            ],
            [
                'name' => 'The Hate You Give',
                'author' => 'Angie Thomas',
                'image' => 'https://bookcart.azurewebsites.net/Upload/3d894fa1-8746-4443-b244-99624cc39f1fq1we.jpg',
                'price' => 227
            ],
            [
                'name' => 'The Martian',
                'author' => 'Andy Weir',
                'image' => 'https://bookcart.azurewebsites.net/Upload/5b7162d6-2780-461b-be6f-e4debac083ad18007564.jpg',
                'price' => 348
            ],
            [
                'name' => 'The Beholder',
                'author' => 'Anna Bright',
                'image' => 'https://bookcart.azurewebsites.net/Upload/5ba1968d-a7f5-4a04-99c2-281088b8532fqq.jpg',
                'price' => 998
            ]
        ];
        foreach ($books as $key => $value) {
            Book::create($value);
        }
    }
}

Execute command to add sample data in the database.

php artisan db:seed --class=BookSeeder

Build Product Controller

Now, we will integrate the cart logic: Make sure to build a new Controller; we will require to add the logic for adding and removing products from the cart.

php artisan make:controller BookController

Furthermore, you have to update the following code within the app/Http/Controllers/BookController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Book;


class BookController extends Controller
{

    public function index()
    {
        $books = Book::all();
        return view('products', compact('books'));
    }
  
    public function bookCart()
    {
        return view('cart');
    }

    public function addBooktoCart($id)
    {
        $book = Book::findOrFail($id);
        $cart = session()->get('cart', []);

        if(isset($cart[$id])) {
            $cart[$id]['quantity']++;
        } else {
            $cart[$id] = [
                "name" => $book->name,
                "quantity" => 1,
                "price" => $book->price,
                "image" => $book->image
            ];
        }

        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Book has been added to cart!');
    }
    
    public function updateCart(Request $request)
    {
        if($request->id && $request->quantity){
            $cart = session()->get('cart');
            $cart[$request->id]["quantity"] = $request->quantity;
            session()->put('cart', $cart);
            session()->flash('success', 'Book added to cart.');
        }
    }
  
    public function deleteProduct(Request $request)
    {
        if($request->id) {
            $cart = session()->get('cart');
            if(isset($cart[$request->id])) {
                unset($cart[$request->id]);
                session()->put('cart', $cart);
            }
            session()->flash('success', 'Book successfully deleted.');
        }
    }
}

Create New Routes

In this step, you will be adding routes in the routes/web.php file.

We will have to add routes to handle displaying the cart and adding and deleting items from the laravel cart.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/dashboard', [BookController::class, 'index']);  
Route::get('/shopping-cart', [BookController::class, 'bookCart'])->name('shopping.cart');
Route::get('/book/{id}', [BookController::class, 'addBooktoCart'])->name('addbook.to.cart');
Route::patch('/update-shopping-cart', [BookController::class, 'updateCart'])->name('update.sopping.cart');
Route::delete('/delete-cart-product', [BookController::class, 'deleteProduct'])->name('delete.cart.product');

Create Cart View

You will now create the view for the cart.

We will build some files, these files will manage the views in our laravel app, and we will display the contents of the cart to the user and allow them to modify the cart contents.

Insert code into the resources/views/shop.blade.php file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Shopping Cart Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
  
<div class="container mt-5">
    <h2 class="mb-3">Laravel Add To Shopping Cart Example</h2>
        
    <div class="col-12">
        <div class="dropdown" >
            <a class="btn btn-outline-dark" href="{{ route('shopping.cart') }}">
               <i class="fa fa-shopping-cart" aria-hidden="true"></i> Cart <span class="badge text-bg-danger">{{ count((array) session('cart')) }}</span>
            </a>
        </div>
    </div>
</div>


<div class="container mt-4">
    @if(session('success'))
        <div class="alert alert-success">
          {{ session('success') }}
        </div> 
    @endif
    @yield('content')
</div>
  
@yield('scripts')
</body>
</html>

Update following code into the resources/views/products.blade.php file:

@extends('shop')
   
@section('content')
    
<div class="row">
    @foreach($books as $book)
        <div class="col-md-3 col-6 mb-4">
            <div class="card">
                <img src="{{ $book->image }}" alt="{{ $book->name }}" class="card-img-top">
                <div class="card-body">
                    <h4 class="card-title">{{ $book->name }}</h4>
                    <p>{{ $book->author }}</p>
                    <p class="card-text"><strong>Price: </strong> ${{ $book->price }}</p>
                    <p class="btn-holder"><a href="{{ route('addbook.to.cart', $book->id) }}" class="btn btn-outline-danger">Add to cart</a> </p>
                </div>
            </div>
        </div>
    @endforeach
</div>
    
@endsection

Put the given code inside the resources/views/cart.blade.php file:

@extends('shop')
  
@section('content')
<table id="cart" class="table table-bordered">
    <thead>
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Total</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @php $total = 0 @endphp
        @if(session('cart'))
            @foreach(session('cart') as $id => $details)
                
                <tr rowId="{{ $id }}">
                    <td data-th="Product">
                        <div class="row">
                            <div class="col-sm-3 hidden-xs"><img src="{{ $details['image'] }}" class="card-img-top"/></div>
                            <div class="col-sm-9">
                                <h4 class="nomargin">{{ $details['name'] }}</h4>
                            </div>
                        </div>
                    </td>
                    <td data-th="Price">${{ $details['price'] }}</td>
                   
                    <td data-th="Subtotal" class="text-center"></td>
                    <td class="actions">
                        <a class="btn btn-outline-danger btn-sm delete-product"><i class="fa fa-trash-o"></i></a>
                    </td>
                </tr>
            @endforeach
        @endif
    </tbody>
    <tfoot>
        <tr>
            <td colspan="5" class="text-right">
                <a href="{{ url('/dashboard') }}" class="btn btn-primary"><i class="fa fa-angle-left"></i> Continue Shopping</a>
                <button class="btn btn-danger">Checkout</button>
            </td>
        </tr>
    </tfoot>
</table>
@endsection
  
@section('scripts')
<script type="text/javascript">
  
    $(".edit-cart-info").change(function (e) {
        e.preventDefault();
        var ele = $(this);
        $.ajax({
            url: '{{ route('update.sopping.cart') }}',
            method: "patch",
            data: {
                _token: '{{ csrf_token() }}', 
                id: ele.parents("tr").attr("rowId"), 
            },
            success: function (response) {
               window.location.reload();
            }
        });
    });
  
    $(".delete-product").click(function (e) {
        e.preventDefault();
  
        var ele = $(this);
  
        if(confirm("Do you really want to delete?")) {
            $.ajax({
                url: '{{ route('delete.cart.product') }}',
                method: "DELETE",
                data: {
                    _token: '{{ csrf_token() }}', 
                    id: ele.parents("tr").attr("rowId")
                },
                success: function (response) {
                    window.location.reload();
                }
            });
        }
    });
  
</script>
@endsection

Add Products to Cart

Invoke the web server and visit the URL in your web browser to access your Laravel application.

php artisan serve
http://127.0.0.1:8000/dashboard

Laravel Bootstrap Add Product to Shopping Cart Tutorial

Conclusion

In this tutorial, we have learned how to create a shopping cart for the Laravel eCommerce application. This guide showed you how to go through every key attractor essential in laravel web development.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.