A DDD Architecture in Laravel — The 4-Layer Structure and Dependency Inversion
Compares traditional Laravel MVC with clean architecture and explains the 4-layer structure (presentation / application / domain / infrastructure), the dependency inversion principle (DIP), the directory layout, and the separation of the Eloquent model from the domain entity.
A Practical Guide to Laravel × DDD × Clean Architecture
No Laravel experience required. A 24-chapter guide for SPA developers (Vue/React) that explains Laravel as an API backend together with domain-driven design (DDD) and clean architecture, step by step. It covers modeling with bounded contexts and EventStorming, the theory of value objects, entities, aggregates, and repositories, through to implementation patterns, transactions, testing, and authentication in a Laravel project.
Authentication — token authentication with Sanctum
Chapter 11 of the Laravel API Development Guide. Builds sign-up, login, and logout with Sanctum and protects routes with token authentication. It covers moving guest orders onto user accounts, token abilities and expiration, and creating an authenticated state in tests.
Authentication and Authorization Design — JWT and the Division of Responsibilities Across Layers
Explains the design of authentication and authorization in DDD and clean architecture. Covers the division of responsibilities where authentication and authorization live in the presentation layer and business rules in the domain layer, the structure of JWT, the implementation with Laravel × tymon/jwt-auth, access/refresh tokens, and role-based authorization.
Authorization — deciding who can do what with Gates and Policies
Chapter 12 of the Laravel API Development Guide. While building the order listing and detail endpoints, it implements per-model authorization with a Policy. It covers why a Policy does not take effect on a listing, choosing between 403 and 404, and detecting authorization gaps with tests.
Basics of Laravel API Development — Controller, FormRequest, Eloquent, DI
An introduction to API backend development for those new to Laravel. It covers routing, controllers, FormRequest, API Resource, Eloquent ORM, the DI container, Sanctum authentication, and the PHP 8.x syntax used in this book (readonly / enum / constructor promotion).
Caching — how much correctness you trade for speed
Chapter 18 of the Laravel API Development Guide. Covers deciding what may be cached, Cache::remember and driver choice, key design, TTLs and explicit invalidation, stampede protection (Cache::flexible and Cache::lock), Laravel 13's Cache::touch, and writing tests that use the cache.
Conclusion and Next Steps — Introducing DDD Incrementally
Organizes the key points of this guide's introduction and all five parts (DDD strategic design / tactical design / clean architecture / practical techniques / a comprehensive hands-on example), and summarizes a roadmap for incremental adoption—value objects → use case layer → repository → domain events—along with frequently asked questions and recommended books, communities, and learning paths.
Dependency injection and the Laravel container — automatic resolution and binding interfaces
Covers how automatic resolution works in the Laravel service container, how bind ties an interface to an implementation class, and how contextual binding switches the implementation per injection site.
Designing the output — deciding the shape of a response with an API Resource
Chapter 7 of the Laravel API Development Guide. Shows the danger of returning the model as is, and pins the response shape down in code with an API Resource. It covers including relationships, conditional fields, how dates, amounts, and enums are represented, and data wrapping.
Designing the Presentation Layer — FormRequest, Thin Controllers, and API Resources
Explains the design of the presentation layer that handles HTTP requests/responses. Covers format validation with FormRequest, the division of responsibilities with the domain layer, conversion to Commands, thin controllers, API Resources, middleware authentication, and Policy authorization.
Designing the Use Case Layer — Command / Query Separation and DTOs
Explains the design of the application layer (use case layer). Covers its responsibilities of coordinating domain objects, managing transactions, and converting input/output; Command / Query separation based on the CQS principle; Command objects and DTOs; dedicated Query services; and design guidelines such as single responsibility.
Domain Events — Loosely Coupling Aggregates
Explains the DDD domain event (Domain Event) with implementation examples such as OrderConfirmed. It covers loose coupling through event-driven design, the two-phase implementation of recording and dispatching, integration with Laravel Events, synchronous vs asynchronous (ShouldQueue), and the design of idempotency and eventual consistency.
Domain Model and Table Design — Mapping and Indexes
Covers why to design domain-model-first, mapping patterns under the premise that the domain model and tables are not 1:1 (embedding / one aggregate across multiple tables / technical splitting), how the repository absorbs the gap, and index design including the leftmost-prefix rule for composite indexes and its trade-offs.
Error design — translating exceptions into HTTP responses
Chapter 9 of the Laravel API Development Guide. Settles the shape of error responses, creates custom exception classes, and makes withExceptions in bootstrap/app.php the one and only conversion point. It also covers what goes to the log and what is never shown to the client.
Error Handling — Mapping Domain Exceptions to HTTP Statuses
Explains error handling in a DDD architecture. Covers an exception hierarchy organized per aggregate, the design of DomainException, mapping to HTTP statuses (404/409/422, etc.) in the Exception Handler, a unified error response, the Result type pattern, a logging strategy, and protecting sensitive information.
Events and notifications — decoupling everything after order confirmation
Chapter 15 of the Laravel API Development Guide. Solves the problem of processing piling up in a service class with events and listeners. It covers listener auto-discovery, Notification classes and Mailables, measuring the cost of synchronous sending, and testing with Notification::fake versus Mail::fake.
Exception design and validation — Form Requests and custom exceptions
Covers checking the shape of a request with a Form Request, and fail-fast design with custom exception classes.
File storage — product images and receipt PDFs
Chapter 19 of the Laravel API Development Guide. Covers the disk abstraction and choosing between local and public, validating and storing uploads, protection with Sanctum abilities, serving private files and signed URLs, generating PDFs in a job, keeping files and records consistent, and testing with Storage::fake.
Getting Started — A Practical Guide to Laravel × DDD × Clean Architecture
An introduction to DDD and clean architecture with Laravel, aimed at developers experienced with SPA development (Vue/React). It covers what you will learn, the e-commerce order system used as the running example, the SPA + API architecture assumed throughout, an overview of DDD and clean architecture, and the books to read alongside.
In Practice: Implementing the Order System — An Example That Cuts Across All Layers
Integrates the DDD and clean architecture learned so far, implementing the 4 layers (presentation / application / domain / infrastructure) using the order creation and confirmation APIs as the subject. Summarizes each layer's responsibilities, the flow of data transformation, and layered tests (domain / UseCase / Repository) to bring the whole picture together.
Introducing Part 2 — what Fat Controller and Fat Model mean
The introduction to Part 2. Pins down what Fat Controller and Fat Model mean, and states the scope of this part (class design only).
Introduction — what we build, and what we leave out
Chapter 1 of the Laravel API Development Guide. Shows three places where an order API written straight from a tutorial breaks in production, and sets out this series' scope, its subject, and how it fits with the existing guides.
Laravel API Development Guide
A 22-chapter guide to using Laravel as an API backend. It works through routing, Eloquent, and validation basics, then authentication and authorization (Sanctum, Policy), caching, queues, the task scheduler, file storage, and production operations, all built around an e-commerce order system. Blade and other frontend features are out of scope.
Logging, monitoring, and deployment — being able to trace what happened
Chapter 21 of the Laravel API Development Guide. Covers channels and stacks in config/logging.php, propagating a request ID with Context, routing expected and unexpected errors, recording 404s and 429s, masking sensitive data with a Monolog processor, structured logs, the order of deployment steps, and health-checking the scheduler.
Middleware and rate limiting — putting cross-cutting defenses in one place
Chapter 13 of the Laravel API Development Guide. Using payment webhook signature verification as the subject, it writes custom middleware and registers it in bootstrap/app.php. It also covers rate limiting with RateLimiter, layered limits, the 429 response, and CORS.
Modeling the subject and seeding data — tables, models, and seeders
Chapter 3 of the Laravel API Development Guide. Creates the products, stock, orders, and order lines tables with migrations, maps Eloquent models to enums, and prepares development data with factories and seeders. It also settles how amounts are typed and how mass assignment is handled.
PHP Class Design Guide
A 14-chapter guide that takes class design in PHP from first principles to practice. It runs from framework-independent design principles (encapsulation, single responsibility, inheritance versus composition, interfaces, SOLID) through to model and service class design in Laravel.
Practice — refactoring class design
Refactors the Fat Controller and Fat Model from chapter 8 end to end, using the criteria from chapters 9 to 12. The practical chapter that puts every Part 1 principle to work.
Queue basics — moving heavy work out of the request
Chapter 16 of the Laravel API Development Guide. Makes a listener asynchronous with ShouldQueue and runs a worker with queue:work. It also covers Job classes and dispatch, choosing a driver, SerializesModels, afterCommit for not dispatching inside a transaction, Queue::route, and testing with Queue::fake.
Queues in production — idempotency, retries, and failed_jobs
Chapter 17 of the Laravel API Development Guide. Covers writing idempotently on the premise that a job runs twice, retry design with Tries and Backoff, failed_jobs and queue:retry, ShouldBeUnique and WithoutOverlapping, and keeping workers alive with Supervisor plus queue:restart.
Responsibilities of an Eloquent model — what belongs and what does not
Sets out the responsibilities an Eloquent model should carry (relationships, accessors and mutators, casts, local scopes) against the ones it should not, contrasted with the Fat Model.
Routing design and your first endpoint
Chapter 4 of the Laravel API Development Guide. Builds the API skeleton with install:api, groups routes with apiResource, and turns IDs into models with route model binding. It also covers URL design, versioning, and choosing status codes.
Splitting responsibilities into service classes — extraction that stops controllers growing
How to decide when to extract the processing left in a controller that coordinates several concerns into a service class. Also covers keeping cohesion so the split does not end up as a mere file split.
Summary — a pre-release checklist
The final chapter of the Laravel API Development Guide. It gathers what the 21 chapters settled into one list to run through before shipping to production, with checklists by area — configuration, database, input and output, authorization, asynchronous work, logging, and deployment — plus an index of which chapter decided what.
Summary — making class design calls at work
Gathers the criteria from all 13 chapters into a checklist you can use when facing real code. Also points to what to read next.
Testing — pinning down the API's contract with Pest
Chapter 10 of the Laravel API Development Guide. Introduces how to write Pest and adds Feature tests to the API built so far. It covers why failure paths matter as much as the happy path, preparing test data, and the testing pattern the rest of the series follows.
Testing Strategy — The Test Pyramid and Layered Testing
Explains the testing strategy for a DDD architecture. Covers the idea of the test pyramid (Unit / Integration / Feature), the benefit of testing the domain layer fast without a DB, minimal use of mocks, Arrange-Act-Assert, descriptive test method names, and the test data builder pattern.
The listing API — pagination, filters, and N+1
Chapter 8 of the Laravel API Development Guide. Using the product listing API, it covers choosing between the three kinds of pagination, safely accepting filters and sorting, observing the N+1 problem and solving it with eager loading, and detecting it mechanically.
The Repository Pattern — The Boundary Between Domain and Persistence
Implements the repository pattern with Laravel + Eloquent. Covers why the interface lives in the domain layer (DIP / testability), one aggregate = one repository, mapping between entities and Eloquent Models, the N+1 problem and eager loading, mass-assignment protection, and registration in the DI container.
The request lifecycle and the skeleton of Laravel 13
Chapter 2 of the Laravel API Development Guide. Follows the path one request takes from public/index.php to the controller, and shows where bootstrap/app.php, the service container, service providers, and the config files plug into that path.
The task scheduler — collapsing scheduled work into a single cron line
Chapter 20 of the Laravel API Development Guide. Covers defining schedules in routes/console.php, why the cron entry stays one line, pruning expired tokens, negative stock, and orphaned files, auto-cancelling unpaid orders and deciding what "unpaid" means, withoutOverlapping and onOneServer, and tests with travelTo plus wiring tests.
Transaction Management — Where to Place the Consistency Boundary
Explains transaction management using Laravel's DB::transaction(). Covers the ACID properties, when to place transactions inside the Repository (single aggregate) versus the UseCase (multiple aggregates), nested transactions (savepoints), and the implementation and use cases of optimistic and pessimistic locking.
Transactions and concurrency — closing double-allocated stock
Chapter 14 of the Laravel API Development Guide. Covers atomicity with DB::transaction, row locks with lockForUpdate, conditional UPDATEs, and retrying on deadlock. It also covers preventing duplicate orders with an Idempotency-Key and a unique constraint.
Validating input — fixing the boundary with a Form Request
Chapter 5 of the Laravel API Development Guide. Using the order creation API, it moves validation written inline in the controller into a Form Request. It covers validating arrays and nested data, hooking in before and after validation, customizing messages, and the line between shape checks and business rules.
Where business logic belongs — service classes and the service container
Chapter 6 of the Laravel API Development Guide. Diagnoses the controller for the order creation API built in the previous chapter and extracts it into a service class. It covers what goes in an Eloquent model and what does not, automatic dependency resolution by the service container, and binding interfaces.
Why DDD — The Limits of the Fat Controller / Fat Model
Organizes the problems that arise when handling complex business logic in traditional Laravel MVC—Fat Controller, Fat Model, and scattered logic—and explains the four benefits gained by adopting DDD: clarifying business rules, resilience to change, testability, and team communication.