Share this:

Hello guys, today we are going to learn Laravel 10 Bootstrap Add Product to Shopping Cart Tutorial. In today’s digital world, e-commerce has become an integral part of our lives. With the growing popularity of online shopping, web developers are constantly striving to create seamless and user-friendly experiences for customers.

Laravel, a powerful PHP framework, has gained immense popularity due to its elegance and simplicity. In this tutorial, we will explore how to use Laravel 10 and Bootstrap to build a shopping cart feature, allowing users to add products to their carts effortlessly.

How to Create an eCommerce Shopping Cart in Laravel 10

  • Step 1: Install Laravel 10 Project
  • Step 2: Add Database Details
  • Step 3: Create Model and Migrations
  • Step 4: Seed Records in Database
  • Step 5: Build Product Controller
  • Step 6: Create New Routes
  • Step 7: Create Cart View
  • Step 8: Testing

Step 1: Install Laravel 10 Project

First, make sure you have Laravel 10 installed on your local development environment. If not, follow the official Laravel documentation for installation instructions. Once Laravel is up and running, create a new Laravel project using the following command in your terminal:

laravel new shopping-cart

or install using composer:

composer create-project laravel/laravel --prefer-dist shopping-cart
Install Laravel 10 Project
Install Laravel 10 Project

Go into the project directory:

cd shopping-cart

Step 2: Add Database Details

For this tutorial, we will use MySQL as our database. Configure your database credentials in the .env file located in the root directory of your Laravel project. Create a new database for this tutorial and update the .env file accordingly.

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

Step 3: Create Model and Migrations

In Laravel, models are used to interact with the database. Let’s create a Product model and migration file by running the following command:

php artisan make:model Product -m
Create Model and Migrations
Create Model and Migrations

app/Models/Product.php

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 
        'description',
        'price'
    ];  
}

database/migrations/xxx_create_products_table.php

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string("name")->nullable();
            $table->longtext("description")->nullable();
            $table->integer("price");  
            $table->timestamps();
        });
    }

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

Now run the migration

php artisan migrate

Step 4: Seed Records in Database

To demonstrate the functionality of our shopping cart, we need a few sample products in our database. We can easily populate the products table by creating a seeder.

Create a seeder: Run the following command to generate a seeder class:

php artisan make:seeder ProductsTableSeeder

This command will generate a new seeder file named ProductsTableSeeder.php in the database/seeders directory.

Modify the seeder class: Open the ProductsTableSeeder.php file and locate the run method. Inside this method, you can use the Laravel Eloquent ORM to create sample product records. For example, you can use the following code snippet to create three sample products:

<?php

namespace Database\Seeders;

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

class ProductsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        Product::create([
            'name' => 'Product 1',
            'price' => 10,
            'description' => 'This is the first sample product.',
        ]);

        Product::create([
            'name' => 'Product 2',
            'price' => 20,
            'description' => 'This is the second sample product.',
        ]);

        Product::create([
            'name' => 'Product 3',
            'price' => 15,
            'description' => 'This is the third sample product.',
        ]);
    }
}

Feel free to modify the product attributes according to your requirements. You can add more products or customize the existing ones as needed.

Run the seeder: To populate the products table with the sample records, run the following command:

php artisan db:seed --class=ProductsTableSeeder

This command will execute the run method within the ProductsTableSeeder class and create the sample product records in your database.

By seeding the database with sample products, we can simulate a real shopping experience in our Laravel application. With the populated products, users can add items to their shopping carts and proceed with their online shopping activities.

Step 5: Build Product Controller

To enable the functionality of displaying, adding and removing products from the cart, we need to create a new controller and implement the necessary logic.

Create a Product Controller: Run the following command to generate a new controller:

php artisan make:controller ProductController

This command will generate a ProductController file in the app/Http/Controllers directory.

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::all();
        return view('products', compact('products'));
    }
  
    public function productCart()
    {
        return view('cart');
    }
    public function addProducttoCart($id)
    {
        $product = Product::findOrFail($id);
        $cart = session()->get('cart', []);
        if(isset($cart[$id])) {
            $cart[$id]['quantity']++;
        } else {
            $cart[$id] = [
                "name" => $product->name,
                "quantity" => 1,
                "price" => $product->price,
                "description" => $product->description
            ];
        }
        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Product 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', 'Product 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', 'Product successfully deleted.');
        }
    }
}

Step 6: Create New Routes

In this section, we will define the routes necessary for our shopping cart functionality in the Laravel project.

Open the routes/web.php file: Located in the root directory of your Laravel project, the routes/web.php file is where you define your application’s routes.

Define the routes for the shopping cart: Add the following routes to the web.php file:

<?php

use Illuminate\Support\Facades\Route;
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('/', function () {
    return view('welcome');
});

Route::get('/dashboard', [ProductController::class, 'index']);  
Route::get('/shopping-cart', [ProductController::class, 'productCart'])->name('shopping.cart');
Route::get('/product/{id}', [ProductController::class, 'addProducttoCart'])->name('addProduct.to.cart');
Route::patch('/update-shopping-cart', [ProductController::class, 'updateCart'])->name('update.sopping.cart');
Route::delete('/delete-cart-product', [ProductController::class, 'deleteProduct'])->name('delete.cart.product');

Step 7: Create Cart View

To provide a user interface for managing the shopping cart, we need to create the necessary view files in our Laravel application.

Navigate to the resources/views directory: In your Laravel project, locate the resources/views directory. This is where we will create our view files.

resources/views/shop.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Shopping Cart Example - LaravelTuts.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <script src="https://kit.fontawesome.com/71b7145720.js" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
</head>
<body>
  
<div class="container mt-5">
    <h2 class="mb-3">Laravel 10 Add To Shopping Cart Example - LaravelTuts.com</h2>
    <div class="col-12">
        <div class="dropdown" >
            <a class="btn btn-outline-dark" href="{{ route('shopping.cart') }}">
                <i class="fa-solid fa-cart-shopping"></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>

resources/views/products.blade.php

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

resources/views/cart.blade.php

@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-12">
                                <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-solid fa-trash"></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

Step 8: Testing

To access your Laravel application through a web browser, you can use the php artisan serve command to start the development server. Here are the steps to follow:

php artisan serve

Test our Laravel 10 Bootstrap Add Product to Shopping Cart Tutorial by opening the following link in browser:

http://127.0.0.1:8000/dashboard
Laravel 10 Bootstrap Add Product to Shopping Cart Tutorial
Laravel 10 Bootstrap Add Product to Shopping Cart Tutorial

Conclusion

In summary, this tutorial demonstrated how to utilize Laravel 10 and Bootstrap to create a seamless shopping cart feature. By following the outlined steps, developers can build a user-friendly eCommerce application that allows users to add and manage products in their carts efficiently. Laravel’s elegance and Bootstrap’s responsive design provide a powerful combination for developing robust and visually appealing shopping cart functionality.

Share this:

Categorized in: