Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 AJAX Add Product to Shopping Cart Tutorial

Last Updated on April 12, 2024 by

In Laravel 11, AJAX allows users to add products to shopping cart without reloading the entire page and the session will store product related information in it.

Let’s start building add product to shopping cart with Ajax and session:

Step 1 – Install Laravel 11

Use the composer command to install new laravel 11 application:

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

Step 2 – Configure Database

Edit .env file from project root folder, and add your database details in it:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_db_name
DB_USERNAME=your_db_user
DB_PASSWORD=your_db_pass

Step 3 – Create Model and Migration

Create model and migration file for add to cart project by using the below given command:

php artisan make:model Product -m

Edit app/models/product.php model and add some property in it:

class Product extends Model
{
    use HasFactory;

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

Define some fields in product table through database/migration/create_products_table.php migration file:

   public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string("name", 255)->nullable();
            $table->text("detail")->nullable();
            $table->string("image", 255)->nullable();
            $table->decimal("price", 6, 2);            
            $table->timestamps();
        });
    }

Run migration to generate tables in database:

php artisan migrate

Step 4 – Create Controller

To create controller class and methods in to it to handle add to cart logic:

php artisan make:controller ProductController

Step 5 – Define Method to Handle Ajax Request

Edit ProductController.php file and define some methods into it to show product list, cart list and handle ajax add to cart logic:

<?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 cartList()
    {
        return view('cart-list');
    }

    public function addProductToCart(Request $request)
    {
        $productId = $request->input('product_id');
        $quantity = $request->input('quantity', 1);
        $cartItemId = $request->input('cart_item_id');

        $productd = Product::find($productId);

        if (!$productd) {
            return response()->json(['error' => 'Prodcut not found'], 404);
        }

        $cart = session()->get('cart', []);

        if (isset($cart[$productId])) {
            // Update quantity if product is already in the cart
            $cart[$productId]['quantity'] += $quantity;
        } else {
            // Add new item to the cart
            $cart[$productId] = [
                'id' => $productd->id,
                'name' => $productd->name,
                'price' => $productd->price,
                'quantity' => $quantity,
                "poster" => $productd->poster
            ];
        }

        session()->put('cart', $cart);

        // Calculate the total quantity
        $totalQuantity = 0;
        foreach ($cart as $item) {
            $totalQuantity += $item['quantity'];
        }
        return response()->json(['message' => 'Cart updated', 'cartCount' => $totalQuantity], 200);
    }

    
    public function deleteItem(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 Routes

Edit routes/web.php file and add routes into it to handle ajax add to cart requests:

use App\Http\Controllers\ProductController;

Route::get('/prodcut-list', [ProductController::class, 'index']);  
Route::get('/cart-list', [ProductController::class, 'cartList']);
Route::post('add-to-cart', [ProductController::class, 'addProductToCart'])->name('add-product-to-shopping-cart');
Route::delete('/delete-cart-product', [ProductController::class, 'deleteItem'])->name('delete.cart.product');

Step 7 – Create Views

To manage add to cart on blade views, need to create some views in resources/views folder.

Create main.blade.php and add the following code into it:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Ajax Add to Shopping Cart Tutorial - Itcodstuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
</head>
<body>
  
<div class="container mt-5">
    <h2 class="mb-3">Laravel 11 Ajax Add to Shopping Cart Tutorial - Itcodstuff.com</h2>
        
    @php
    $totalQuantity = 0;
    @endphp
    
    @if(session('cart'))
    @foreach(session('cart') as $item)
        @php
        $totalQuantity += $item['quantity'];
        @endphp
    @endforeach
    @endif

    <div class="col-12">
        <div class="dropdown" >
            <a class="btn btn-outline-dark" href="{{ url('cart-list') }}">
               <i class="fa fa-shopping-cart" aria-hidden="true"></i> Cart <span class="badge text-bg-danger" id="cart-quantity">{{ $totalQuantity }}</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>

Create products.blade.php file to show all products on list:

@extends('main')
   
@section('content')
    
<div class="row">
    @foreach($products as $prodt)
        <div class="col-md-3 col-6 mb-4">
            <div class="card">
                <img src="{{ $prodt->image }}" alt="{{ $prodt->name }}" class="card-img-top">
                <div class="card-body">
                    <h4 class="card-title">{{ $prodt->name }}</h4>
                    <p>{{ $prodt->detail }}</p>
                    <input type="hidden" class="product-quantity" value="1">
    <p class="btn-holder"><button class="btn btn-outline-danger add-to-cart" data-product-id="{{ $prodt->id }}">Add to cart</button></p>
                </div>
            </div>
        </div>
    @endforeach
</div>
@endsection

Create a cart.blade.php file to show all products that have been added to the cart by the user:

@extends('main')
  
@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 => $item)
                
                <tr rowId="{{ $id }}">
                    <td data-th="Product">
                        <div class="row">
                            <div class="col-sm-3 hidden-xs"><img src="{{ isset($item['image']) ? $item['image'] : 'N/A' }}" class="card-img-top"/></div>
                            <div class="col-sm-9">
                                <h4 class="nomargin">{{ $item['name'] }}</h4>
                            </div>
                        </div>
                    </td>
                    <td data-th="Price">${{ $item['price'] }}</td>
                   
                    <td data-th="Subtotal" class="text-center">${{ $item['price'] * $item['quantity'] }}</td>
                    <td class="actions">
                        <a class="btn btn-outline-danger btn-sm delete-item">Delete</a>
                    </td>
                </tr>
            @endforeach
        @endif
    </tbody>
    <tfoot>
        <tr>
            <td colspan="5" class="text-right">
                <a href="{{ url('/prodcut-list') }}" 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

Step 8 – Implement AJAX Functionality

Now implement Ajax functionality that allows users to add and remove products from cart.

Edit products.blade.php file and add the following that allows users to add product in cart:

@section('scripts')

<script type="text/javascript">
    $(".add-to-cart").click(function (e) {
        e.preventDefault();

        var productId = $(this).data("product-id");
        var productQuantity = $(this).siblings(".product-quantity").val();
        var cartItemId = $(this).data("cart-item-id");

        $.ajax({
            url: "{{ route('add-product-to-shopping-cart') }}",
            method: "POST",
            data: {
                _token: '{{ csrf_token() }}', 
                product_id: productId,
                quantity: productQuantity,
                cart_item_id: cartItemId
            },
            success: function (response) {
                $('#cart-quantity').text(response.cartCount);
                 alert('Cart Updated');
                console.log(response);
            },
            error: function (xhr, status, error) {
                // Handle errors (e.g., display an error message)
                console.error(xhr.responseText);
            }
        });
    });
</script>


@endsection

Edit cart.blade.php file and add the following that allows users to remove product from cart:

@section('scripts')
<script type="text/javascript">
  
    $(".delete-item").click(function (e) {
        e.preventDefault();
  
        var ele = $(this);
  
        if(confirm("Do you really want to delete?")) {
            $.ajax({
                url: '{{ route('delete.cart.item') }}',
                method: "DELETE",
                data: {
                    _token: '{{ csrf_token() }}', 
                    id: ele.parents("tr").attr("rowId")
                },
                success: function (response) {
                    window.location.reload();
                }
            });
        }
    });
  
</script>
@endsection

Step 9 – Insert Products in Database

Create a seeder file in the project that will help you insert or add some data to your database:

php artisan make:seed ProductSeeder

Edit the productSeeder.php file in database/seeders folder and add the record you want to insert into your database:

 public function run(): void
    {
       $Products = [
            [
                'name' => 'Hancock Movie',
                'detail' => 'Peter Hennry',
                'image' => 'https://assets-in.bmscdn.com/iedb/movies/images/extra/vertical_logo/mobile/thumbnail/xxlarge/hancock-et00000995-10-03-2021-03-48-47.jpg',
                'price' => 299
            ],
            [
                'name' => 'POST 370 Movie',
                'detail' => 'Aditya Suhas',
                'image' => 'https://assets-in.bmscdn.com/iedb/movies/images/mobile/thumbnail/xlarge/article-370-et00384444-1708669471.jpg',
                'price' => 500
            ],
            [
                'name' => 'RAO Movie',
                'detail' => 'Rajkumar RAO',
                'image' => 'https://assets-in.bmscdn.com/iedb/movies/images/mobile/thumbnail/xlarge/yuva-et00387718-1708087150.jpg',
                'price' => 1000
            ],
            [
                'name' => 'JSON WORLD',
                'detail' => 'John',
                'image' => 'https://assets-in.bmscdn.com/iedb/movies/images/extra/vertical_logo/mobile/thumbnail/xxlarge/over-water-s1-et00359269-1683705409.jpg',
                'price' => 699
            ],
            [
                'name' => 'SHARK TANK ',
                'detail' => 'SHARK Trek',
                'image' => 'https://assets-in.bmscdn.com/iedb/movies/images/extra/vertical_logo/mobile/thumbnail/xxlarge/star-trek-et00003082-14-05-2021-11-30-13.jpg',
                'price' => 649
            ]
        ];
        foreach ($Products as $key => $value) {
            Movie::create($value);
        }
    }

Run this seeder command to insert or append data using seeder file:

php artisan db:seed --class=ProductSeeder

Step 10 – Test Application

Start application server using artisan serve command:

php artisan serve

Hit http://127.0.0.1:8000/prodcut-list url on browser for test this application.

Using this tutorial you can create an e-commerce website in Laravel 11 where users can select the product and add it to shopping cart they want to purchase.

Leave a Comment