Skip to main content

47 docs tagged with "laravel"

View all tags

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.