DEV Community

Cover image for How I Saved 40+ Hours Building a Production-Ready Laravel 11 E-Commerce REST API
zinh8803
zinh8803

Posted on Edited on Originally published at vinhcraft17.gumroad.com

How I Saved 40+ Hours Building a Production-Ready Laravel 11 E-Commerce REST API

Starting a new client project or e-commerce web application often means repeating the same foundational setup: configuring authentication with access and refresh tokens, setting up rate limiting, building data repositories, integrating payment gateways, and wiring up realtime WebSockets.

Before writing a single line of domain logic, developers easily spend 30 to 40 hours just on boilerplate configuration.

To streamline this workflow, I engineered and tested a production-ready Laravel 11 Backend Starter Kit designed for e-commerce and composite inventory stores.

Below is an overview of the architectural decisions, security practices, and workflow designs implemented in this codebase.

Clean Architecture: Repository and Service Pattern

While Laravel permits business logic directly inside controllers, doing so in complex e-commerce applications quickly leads to unmaintainable code.

This project implements a strict separation of concerns:

HTTP Request -> FormRequest (Validation) -> Controller -> Service Layer -> Repository Layer -> Eloquent Model

Controllers: Handle HTTP transport, invoke service methods, and return structured JSON responses.

Services (app/Services/): Contain business rules, composite inventory calculations, payment signatures, and job dispatching.

Repositories (app/Repositories/): Abstract database interactions through interfaces (ProductRepositoryInterface, OrderRepositoryInterface), registered via RepositoryServiceProvider.

This structure allows swapping storage engines and writing isolated unit tests with ease.

Authentication and Role-Based Access Control (RBAC)

Modern APIs serve both single-page applications (SPAs) and native mobile clients simultaneously.

Dual-Mode JWT Authentication:
The authentication middleware supports two delivery mechanisms:

Bearer Tokens (Authorization: Bearer ) for mobile clients and tools like Postman or Bruno.

HttpOnly Cookies for browser clients to prevent XSS-based token theft.

Role-Based Access Control:
The RBAC middleware restricts access based on user roles:

admin: Full control over employee management, inventory configurations, and user accounts.

employee: Access to order fulfillment, stock imports, and reports.

user: Standard customer capabilities.

Recipe-Based Dynamic Inventory Management

Traditional e-commerce platforms often track stock using a simple quantity column on the product table. However, composite stores craft finished goods from raw components.

Example: A Luxury Rose Bouquet (Size M) requires:

10x Red Roses

5x Baby's Breath

1x Packaging Material

The inventory service calculates real-time craftable stock by querying raw material shipments. When an order is created, raw material stock is deducted inside an atomic database transaction.

Automated Daily Stock Importer:
Through Laravel's scheduler (php artisan schedule:work), the console command import-receipt:auto-create processes configured daily stock arrivals at specified hours and broadcasts alerts to staff.

Payment Processing and Webhook Verification

Payment processing requires cryptographic verification to prevent spoofed transactions.

The starter kit provides end-to-end flows for payment gateways with signature validation:

Checkout Session: Generates signed checkout URLs using HMAC-SHA512.

Webhook / IPN Verification: Sorts incoming parameters, recomputes the expected signature, and uses hash_equals() to prevent timing attacks. Updates order status to PAID only upon valid signature verification and returns 400 Bad Request if the payload is forged or tampered with.

Realtime WebSockets with Pusher

The backend connects to Pusher Channels for immediate UI synchronization:

admin-orders channel: Triggers instant notifications when a customer completes an order.

admin-auto-imports channel: Alerts staff when the scheduled import command executes.

private-chat.{userId} channel: Facilitates private customer support conversations.

All event broadcasts and transactional emails are queued (php artisan queue:work) to ensure API response latency stays under 50ms.

Security Hardening and Quality Assurance

The codebase includes an automated test suite covering 19 end-to-end scenarios:

Rate Limiting: The login endpoint is protected with throttle:login (10 requests/minute). Repeated failures immediately trigger HTTP 429 Too Many Requests.

SQL Injection and XSS Protection: Prepared statements prevent SQL injection attacks, while custom middleware removes script tags from payloads and adds security headers (X-Content-Type-Options: nosniff, X-Frame-Options: DENY, X-XSS-Protection: 1; mode=block).

File Upload Validation: Provides Cloudinary integration with local disk fallback. File uploads are strictly validated for MIME types (PNG, JPG, WEBP, PDF) and size (under 2MB).

Getting the Starter Kit

This project is packaged as a ready-to-deploy boilerplate.

Included Components:

Full Laravel 11.x source code (PSR-4 compliant)

50+ Database Migrations and Seeders (pre-configured Admin and Demo users)

Ready-to-import Postman / Bruno Collection (postman_collection.json)

Interactive Swagger OpenAPI Documentation (/api/documentation)

Complete setup documentation in English and Vietnamese

Multi-container Docker Compose configuration (app, queue, schedule)

Product Link on Gumroad:
https://vinhcraft17.gumroad.com/l/laravel-ecommerce-starter-kit

If you have questions regarding the architecture or implementation details, feel free to leave a comment below.

Top comments (0)