Backend

Building E-commerce with Laravel

Mayur Dabhi
Mayur Dabhi
May 24, 2026
16 min read

A small store looks easy until the first real order comes in. The customer pays, closes the tab before the redirect finishes, and now you've got money in Stripe and an order stuck on "pending". Or two people buy the last item at the same moment and you've sold stock you don't have. Most of the work in e-commerce is in those edges, not in the product grid.

This post builds a working store on Laravel 11: a product catalog, a session cart, Stripe Checkout, webhook-confirmed orders, and a small admin panel. I'll point out the places where the simple version breaks and what I do about it.

What You'll Build

Product browsing with filters and search, a session cart, Stripe Checkout for payments, an order history page for customers, and an admin dashboard for products and orders. Everything runs on Laravel 11 with Breeze for auth.

Project Setup

Start with a fresh Laravel installation and configure the database. We'll use MySQL, though SQLite works fine for local development.

1

Create the Laravel project

Scaffold a new app, install dependencies, and run the dev server.

Terminal
composer create-project laravel/laravel ecommerce
cd ecommerce

# Install Stripe PHP SDK
composer require stripe/stripe-php

# Install Laravel Breeze for auth scaffolding
composer require laravel/breeze --dev
php artisan breeze:install blade
npm install && npm run build

php artisan serve
2

Configure environment variables

Set your database credentials and Stripe API keys in .env.

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ecommerce
DB_USERNAME=root
DB_PASSWORD=

STRIPE_KEY=pk_test_your_publishable_key
STRIPE_SECRET=sk_test_your_secret_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
3

Add Stripe config

Expose Stripe keys through Laravel's config system so they can be cached.

config/services.php (add inside the array)
'stripe' => [
    'key'    => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
    'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
],

Database Design

You need four tables here: categories, products, orders, and order line items. The cart lives in the session, so it doesn't get a table yet. Keeping order_items as a separate table (rather than a JSON column) means you can query and report on sales per product without parsing blobs.

categories id (PK) name slug description products id (PK) category_id (FK) name slug price stock image / description orders id (PK) user_id (FK) status total stripe_session_id shipping_address order_items id (PK) order_id (FK) product_id (FK) quantity / price

The store schema. Order items get their own table so sales reports are plain SQL.

Migrations

database/migrations/create_categories_table.php
Schema::create('categories', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('slug')->unique();
    $table->text('description')->nullable();
    $table->timestamps();
});
database/migrations/create_products_table.php
Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->foreignId('category_id')->constrained()->cascadeOnDelete();
    $table->string('name');
    $table->string('slug')->unique();
    $table->text('description')->nullable();
    $table->decimal('price', 10, 2);
    $table->unsignedInteger('stock')->default(0);
    $table->string('image')->nullable();
    $table->boolean('is_active')->default(true);
    $table->timestamps();
});
database/migrations/create_orders_table.php
Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('status')->default('pending'); // pending|paid|shipped|cancelled
    $table->decimal('total', 10, 2);
    $table->string('stripe_session_id')->nullable();
    $table->json('shipping_address');
    $table->timestamps();
});

Schema::create('order_items', function (Blueprint $table) {
    $table->id();
    $table->foreignId('order_id')->constrained()->cascadeOnDelete();
    $table->foreignId('product_id')->constrained()->restrictOnDelete();
    $table->unsignedInteger('quantity');
    $table->decimal('price', 10, 2); // snapshot of price at purchase time
    $table->timestamps();
});
Snapshot Prices

Store the price in order_items at the time of purchase instead of reading it from the product later. Prices change, and when they do, last month's orders shouldn't change with them.

Shopping Cart Implementation

I start most stores with a session cart. Guests can use it without logging in, it needs no extra tables, and it's fast. The catch is that it doesn't follow the user to another device, which is fine until someone asks for it. All the cart logic goes in a CartService class so the controllers stay thin and you can swap the storage later.

Approach Persists across devices? Requires login? Complexity
Session-basedNoNoLow
Database-backedYesYes (or guest token)Medium
Cookie-basedPartiallyNoLow to Medium
Redis-backedYes (TTL)No (session key)Medium
app/Services/CartService.php
<?php

namespace App\Services;

use App\Models\Product;
use Illuminate\Support\Facades\Session;

class CartService
{
    private const KEY = 'cart';

    public function items(): array
    {
        return Session::get(self::KEY, []);
    }

    public function add(Product $product, int $quantity = 1): void
    {
        $cart = $this->items();
        $id = $product->id;

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

        Session::put(self::KEY, $cart);
    }

    public function update(int $productId, int $quantity): void
    {
        $cart = $this->items();

        if ($quantity <= 0) {
            $this->remove($productId);
            return;
        }

        $cart[$productId]['quantity'] = $quantity;
        Session::put(self::KEY, $cart);
    }

    public function remove(int $productId): void
    {
        $cart = $this->items();
        unset($cart[$productId]);
        Session::put(self::KEY, $cart);
    }

    public function clear(): void
    {
        Session::forget(self::KEY);
    }

    public function total(): float
    {
        return array_reduce($this->items(), function (float $carry, array $item) {
            return $carry + ($item['price'] * $item['quantity']);
        }, 0.0);
    }

    public function count(): int
    {
        return array_sum(array_column($this->items(), 'quantity'));
    }
}

Cart Controller

app/Http/Controllers/CartController.php
<?php

namespace App\Http\Controllers;

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

class CartController extends Controller
{
    public function __construct(private CartService $cart) {}

    public function index()
    {
        return view('cart.index', [
            'items' => $this->cart->items(),
            'total' => $this->cart->total(),
        ]);
    }

    public function add(Request $request, Product $product)
    {
        $request->validate(['quantity' => 'required|integer|min:1|max:99']);
        $this->cart->add($product, $request->quantity);

        return back()->with('success', "{$product->name} added to cart.");
    }

    public function update(Request $request, int $productId)
    {
        $request->validate(['quantity' => 'required|integer|min:0']);
        $this->cart->update($productId, $request->quantity);

        return back()->with('success', 'Cart updated.');
    }

    public function remove(int $productId)
    {
        $this->cart->remove($productId);
        return back()->with('success', 'Item removed.');
    }
}

Binding CartService in the Service Container

Register CartService as a singleton so the same instance is shared within a single request. That helps when multiple controllers or view composers need the cart count.

app/Providers/AppServiceProvider.php
use App\Services\CartService;

public function register(): void
{
    $this->app->singleton(CartService::class);
}

Stripe Payment Integration

I use Stripe Checkout (Stripe's hosted payment page) instead of a custom card form. Card data never touches your server, which keeps your PCI-DSS burden to the simplest self-assessment level. You give up some control over the look of the payment page, and for most stores that's a good trade.

Customer Laravel creates session Stripe Checkout page Webhook confirms payment

Stripe Checkout flow: your server creates the session and handles the webhook. It never sees raw card data.

app/Http/Controllers/CheckoutController.php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\CartService;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Checkout\Session as StripeSession;

class CheckoutController extends Controller
{
    public function __construct(private CartService $cart) {}

    public function create(Request $request)
    {
        $items = $this->cart->items();

        if (empty($items)) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty.');
        }

        Stripe::setApiKey(config('services.stripe.secret'));

        $lineItems = array_map(fn($item) => [
            'price_data' => [
                'currency'     => 'usd',
                'unit_amount'  => (int) round($item['price'] * 100), // cents
                'product_data' => ['name' => $item['name']],
            ],
            'quantity' => $item['quantity'],
        ], $items);

        // Create a pending order before redirecting to Stripe
        $order = Order::create([
            'user_id'          => $request->user()->id,
            'status'           => 'pending',
            'total'            => $this->cart->total(),
            'shipping_address' => $request->only(['line1', 'city', 'postal_code', 'country']),
        ]);

        foreach ($items as $item) {
            $order->items()->create([
                'product_id' => $item['id'],
                'quantity'   => $item['quantity'],
                'price'      => $item['price'],
            ]);
        }

        $session = StripeSession::create([
            'payment_method_types' => ['card'],
            'line_items'           => $lineItems,
            'mode'                 => 'payment',
            'success_url'          => route('checkout.success') . '?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url'           => route('cart.index'),
            'metadata'             => ['order_id' => $order->id],
        ]);

        $order->update(['stripe_session_id' => $session->id]);

        return redirect($session->url, 303);
    }

    public function success(Request $request)
    {
        $this->cart->clear();
        return view('checkout.success');
    }
}

Stripe Webhook Handler

Don't mark an order paid from the success_url redirect. People close the tab, lose their connection, or hit back. The webhook is the only signal you should trust for payment confirmation.

app/Http/Controllers/WebhookController.php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Stripe\Webhook;
use Stripe\Exception\SignatureVerificationException;

class WebhookController extends Controller
{
    public function handle(Request $request)
    {
        $payload = $request->getContent();
        $sig     = $request->header('Stripe-Signature');
        $secret  = config('services.stripe.webhook_secret');

        try {
            $event = Webhook::constructEvent($payload, $sig, $secret);
        } catch (SignatureVerificationException) {
            return response('Invalid signature', 400);
        }

        if ($event->type === 'checkout.session.completed') {
            $session = $event->data->object;
            $orderId = $session->metadata->order_id ?? null;

            if ($orderId) {
                Order::where('id', $orderId)
                     ->where('status', 'pending')
                     ->update(['status' => 'paid']);
            }
        }

        return response('OK', 200);
    }
}

Register the webhook route outside the auth middleware group and exempt it from CSRF verification:

Two webhook gotchas

On Laravel 11 there's no app/Http/Middleware/VerifyCsrfToken.php in a fresh app, so the class reference below won't resolve as written. Either use \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class or exclude the path in bootstrap/app.php with $middleware->validateCsrfTokens(except: ['webhook/stripe']). If you skip this, Stripe gets a 419 and keeps retrying. Also, when testing locally with stripe listen --forward-to, the CLI prints its own whsec_... secret. Put that one in .env, not the one from the dashboard, or every event fails with "No signatures found matching the expected signature for payload".

routes/web.php
// Public routes
Route::get('/products', [ProductController::class, 'index'])->name('products.index');
Route::get('/products/{product:slug}', [ProductController::class, 'show'])->name('products.show');

// Cart routes
Route::prefix('cart')->name('cart.')->group(function () {
    Route::get('/', [CartController::class, 'index'])->name('index');
    Route::post('/add/{product}', [CartController::class, 'add'])->name('add');
    Route::patch('/update/{productId}', [CartController::class, 'update'])->name('update');
    Route::delete('/remove/{productId}', [CartController::class, 'remove'])->name('remove');
});

// Authenticated checkout
Route::middleware('auth')->group(function () {
    Route::post('/checkout', [CheckoutController::class, 'create'])->name('checkout.create');
    Route::get('/checkout/success', [CheckoutController::class, 'success'])->name('checkout.success');
    Route::get('/orders', [OrderController::class, 'index'])->name('orders.index');
});

// Stripe webhook: no auth, no CSRF
Route::post('/webhook/stripe', [WebhookController::class, 'handle'])
    ->withoutMiddleware(['auth', \App\Http\Middleware\VerifyCsrfToken::class]);

// Admin
Route::middleware(['auth', 'admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('dashboard');
    Route::resource('products', AdminProductController::class);
    Route::resource('orders', AdminOrderController::class)->only(['index', 'show', 'update']);
});

Product Catalog & Models

The models are mostly relationships and casts. Binding routes on the slug column gives you readable URLs like /products/wireless-headphones without any controller boilerplate.

app/Models/Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Product extends Model
{
    protected $fillable = [
        'category_id', 'name', 'slug', 'description',
        'price', 'stock', 'image', 'is_active',
    ];

    protected $casts = [
        'price'     => 'decimal:2',
        'is_active' => 'boolean',
    ];

    // Use slug for route model binding
    public function getRouteKeyName(): string
    {
        return 'slug';
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    public function orderItems(): HasMany
    {
        return $this->hasMany(OrderItem::class);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true)->where('stock', '>', 0);
    }
}
app/Models/Order.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Order extends Model
{
    protected $fillable = [
        'user_id', 'status', 'total', 'stripe_session_id', 'shipping_address',
    ];

    protected $casts = [
        'total'            => 'decimal:2',
        'shipping_address' => 'array',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function items(): HasMany
    {
        return $this->hasMany(OrderItem::class);
    }

    public function isPaid(): bool
    {
        return $this->status === 'paid';
    }
}

Product Controller

app/Http/Controllers/ProductController.php
<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $query = Product::active()->with('category');

        if ($request->filled('category')) {
            $query->whereHas('category', fn($q) => $q->where('slug', $request->category));
        }

        if ($request->filled('search')) {
            $term = '%' . $request->search . '%';
            $query->where(fn($q) => $q->where('name', 'like', $term)
                                      ->orWhere('description', 'like', $term));
        }

        $sortMap = [
            'price_asc'  => ['price', 'asc'],
            'price_desc' => ['price', 'desc'],
            'newest'     => ['created_at', 'desc'],
        ];
        [$col, $dir] = $sortMap[$request->sort] ?? ['name', 'asc'];

        $products   = $query->orderBy($col, $dir)->paginate(12)->withQueryString();
        $categories = Category::orderBy('name')->get();

        return view('products.index', compact('products', 'categories'));
    }

    public function show(Product $product)
    {
        $related = Product::active()
            ->where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->limit(4)
            ->get();

        return view('products.show', compact('product', 'related'));
    }
}

Admin Dashboard

You don't need Nova or Filament to see sales, low stock, and pending orders. A couple of controllers will do. The admin routes are protected by a small middleware that checks an is_admin flag on the user (add that boolean column to users yourself). On Laravel 11, register the admin alias in bootstrap/app.php with $middleware->alias(['admin' => EnsureAdmin::class]), otherwise you'll get "Target class [admin] does not exist."

app/Http/Middleware/EnsureAdmin.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnsureAdmin
{
    public function handle(Request $request, Closure $next)
    {
        if (!$request->user()?->is_admin) {
            abort(403);
        }

        return $next($request);
    }
}
app/Http/Controllers/AdminController.php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Product;

class AdminController extends Controller
{
    public function dashboard()
    {
        return view('admin.dashboard', [
            'totalRevenue'   => Order::where('status', 'paid')->sum('total'),
            'totalOrders'    => Order::where('status', 'paid')->count(),
            'pendingOrders'  => Order::where('status', 'pending')->count(),
            'lowStockCount'  => Product::where('stock', '<=', 5)->where('is_active', true)->count(),
            'recentOrders'   => Order::with('user')->latest()->limit(10)->get(),
        ]);
    }
}

Updating Order Status

app/Http/Controllers/AdminOrderController.php (update method)
public function update(Request $request, Order $order)
{
    $request->validate([
        'status' => 'required|in:pending,paid,shipped,cancelled',
    ]);

    $order->update(['status' => $request->status]);

    return back()->with('success', "Order #{$order->id} marked as {$request->status}.");
}

Security Checks for a Store

Laravel gives you CSRF protection and parameter binding in the query builder for free. A store that takes money needs a few more things on top of that.

Safe stock decrement inside a transaction
use Illuminate\Support\Facades\DB;

DB::transaction(function () use ($order, $items) {
    foreach ($items as $item) {
        $affected = Product::where('id', $item['id'])
            ->where('stock', '>=', $item['quantity'])
            ->decrement('stock', $item['quantity']);

        if ($affected === 0) {
            throw new \RuntimeException("Insufficient stock for product #{$item['id']}");
        }
    }
    $order->update(['status' => 'paid']);
});
Environment Variables in Production

Never commit your .env file. Use your hosting platform's secrets manager (Laravel Forge environment, AWS Parameter Store, etc.) to inject STRIPE_SECRET and STRIPE_WEBHOOK_SECRET at runtime. Rotate keys right away if they ever leak.

When I'd Build This Myself (and When I Wouldn't)

A custom Laravel store makes sense when the shop is part of a bigger app you already run, or when the business rules are odd enough that a hosted platform fights you: custom pricing per customer, bundles built from your own inventory system, B2B invoicing. You own the code, the data, and the checkout flow, and Stripe still does the hard part of card processing.

I wouldn't build this for a plain catalog store with standard shipping and taxes. Shopify or WooCommerce already handle tax rules, shipping rates, refunds, discount codes, abandoned carts and order emails, and every one of those is real work you'd be signing up for. None of them are in this post.

What to check before going to production

  • Pending orders from abandoned checkouts pile up. Schedule a job to cancel ones older than a day or so, or listen for checkout.session.expired.
  • Stripe can send the same webhook more than once. The where('status', 'pending') guard keeps the status update idempotent, but anything you add later (emails, stock changes) needs the same care.
  • Register the production webhook endpoint in the Stripe dashboard and use its signing secret, which differs from your local CLI secret.
  • Money is stored as decimal and converted to cents with round(). Keep it that way, and don't do price maths with floats anywhere else.
  • Image uploads (Storage with S3), order confirmation emails on a queue, and search with Laravel Scout are the next things most stores need.
Laravel E-commerce PHP Stripe Shopping Cart Project
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.