Building E-commerce with Laravel
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.
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.
Create the Laravel project
Scaffold a new app, install dependencies, and run the dev server.
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
Configure environment variables
Set your database credentials and Stripe API keys in .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
Add Stripe config
Expose Stripe keys through Laravel's config system so they can be cached.
'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.
The store schema. Order items get their own table so sales reports are plain SQL.
Migrations
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->timestamps();
});
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();
});
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();
});
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-based | No | No | Low |
| Database-backed | Yes | Yes (or guest token) | Medium |
| Cookie-based | Partially | No | Low to Medium |
| Redis-backed | Yes (TTL) | No (session key) | Medium |
<?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
<?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.
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.
Stripe Checkout flow: your server creates the session and handles the webhook. It never sees raw card data.
<?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.
<?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:
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".
// 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.
<?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);
}
}
<?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
<?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."
<?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);
}
}
<?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
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.
- Server-side prices: Never trust a price sent from the browser. The cart above stores
$product->pricefrom the database when the item is added, not a form field. Be aware that this price can go stale if you edit the product while it sits in someone's cart, so re-read prices from the database inCheckoutController::create()if that matters to you. - Stock decrement inside a transaction: Use
DB::transaction()when you decrement stock so two concurrent buyers can't both take the last unit. ACHECK (stock >= 0)constraint in the database is a good backstop (MySQL only enforces CHECK constraints from 8.0.16 on). The snippet below fits naturally inside the webhook handler, in place of the plain status update. - Verify webhook signatures: Always call
Webhook::constructEvent()with the signing secret. Without this check, anyone can POST a fakecheckout.session.completedevent and mark orders paid without paying. - Rate-limit checkout: Put
throttle:5,1on the checkout route. Every request creates a pending order and a Stripe session, so a bot can fill your tables quickly. - Scope order queries to the authenticated user: In
OrderController::show(), add->where('user_id', auth()->id())(or use a policy). Without it, changing the ID in the URL shows someone else's order, which is a textbook IDOR (insecure direct object reference) bug.
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']);
});
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
decimaland converted to cents withround(). Keep it that way, and don't do price maths with floats anywhere else. - Image uploads (
Storagewith S3), order confirmation emails on a queue, and search with Laravel Scout are the next things most stores need.