
A Pragmatic Laravel DDD with Actions, Data Objects & Invokables Guide
A pragmatic, API-first take on Domain-Driven Design in Laravel — actions, data objects, invokable controllers, queued batches, and vendor adapters. Inspired by Spatie Beyond CRUD, adapted for real-world projects.
This document defines how engineers (and AI coding agents) should design and implement business capabilities in a Laravel application.
It’s inspired by Spatie’s Laravel Beyond CRUD book, with explicit src/Domain/<DomainName>/ boundaries — but pared back from the full Spatie package stack. No laravel-data, no laravel-model-states, no laravel-view-models. Just clean folders, plain DTOs, and invokable actions.
Copy this into AGENTS.md at the project root and adapt as needed — or install it as an agent skill straight from robmellett/skills/laravel-ddd, which tracks this guide.
Updated November 2026: Payloads are now Data objects, built by a Form Request’s
toData()method. Actions can exposeexecute()instead of__invoke(). There are new sections on Batches for large datasets and vendor integrations insrc/Support/, and the naming table and checklist cover both.
1. Purpose
A domain represents a coherent business capability — Subscriber, Order, Invoice, Automation. Each domain owns its actions, data objects, models, and enums, and exposes Actions as its public API.
Goal: the folder tree should read like the product owner’s vocabulary, and a new engineer should find any business operation in under 10 seconds.
2. Where Things Live
Domain code lives in src/Domain/<DomainName>/ — one folder per business capability. HTTP plumbing (controllers, requests, responses) stays in app/Http/, but everything that describes the business model — actions, data objects, models, enums — sits inside its domain. Wrappers around third-party SDKs get their own home in src/Support/<VendorName>/.
Add the namespaces to composer.json:
"autoload": {
"psr-4": {
"App\\": "app/",
"Domain\\": "src/Domain/",
"Shared\\": "src/Shared/",
"Support\\": "src/Support/"
}
}
Then run composer dump-autoload.
src/Domain/<DomainName>/
├── Actions/ ← business operations
├── Data/ ← typed DTOs (consumed by HTTP, Jobs, CLI)
├── Models/ ← Eloquent — data access only
├── Enums/ ← status, type, role values
├── Batches/ ← queued jobs that walk large datasets (optional)
├── Contracts/ ← interfaces a vendor adapter implements (optional)
├── Events/ ← domain events (optional)
└── Exceptions/ ← domain exceptions (optional)
src/Support/<VendorName>/ ← third-party SDK adapters, one folder per vendor
app/Http/
├── Controllers/<Domain>/V1/ ← invokable, versioned
├── Requests/<Domain>/V1/ ← validation + toData()
└── Responses/ ← shared Responsable classes
| Layer | Folder | Responsibility |
|---|---|---|
| Domain | src/Domain/<Name>/Actions/ |
One business operation per class |
| Domain | src/Domain/<Name>/Data/ |
final readonly DTOs with a toArray() |
| Domain | src/Domain/<Name>/Models/ |
Eloquent, casts, relationships — no business logic |
| Domain | src/Domain/<Name>/Enums/ |
Status, type, role values |
| Domain | src/Domain/<Name>/Batches/ |
Self-appending queued jobs that walk a large table |
| Support | src/Support/<Vendor>/ |
Translate a vendor SDK to and from the app’s Data objects |
| HTTP | app/Http/Controllers/<Name>/V1/ |
Wire request → action → response. Nothing else. |
| HTTP | app/Http/Requests/<Name>/V1/ |
Validation rules + a toData() method |
| HTTP | app/Http/Responses/ |
Responsable classes (e.g. JsonDataResponse) |
Rule of thumb: if a file would still make sense in a queue worker or CLI command, it belongs in
src/Domain/. If it only exists to serve HTTP, it lives inapp/Http/. If it only exists to talk to Stripe, it lives insrc/Support/Stripe/.
3. Core Rules
1. Business-First Naming
Use the language the business uses. Rename technical defaults:
User → Customer
Job → Broadcast
Task → AutomationStep
If a folder name wouldn’t make sense to a non-engineer, rename it.
2. Invokable Controllers
One controller per operation, one __invoke() method. Versioned under V1/, V2/ so you can ship breaking changes safely.
final class StoreTaskController
{
public function __invoke(StoreTaskRequest $request, CreateTaskAction $action): JsonDataResponse
{
$task = $action($request->toData());
return new JsonDataResponse($task);
}
}
Rule: Controllers have one job — wire the request to the action and shape the response. No business logic, no model writes.
3. Form Requests Carry the DTO
Validation belongs in FormRequest. The same class builds the typed Data object through toData() — the controller never touches $request->all() or $request->validated().
final class StoreTaskRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:200'],
'due_at' => ['nullable', 'date'],
'priority' => ['required', new Enum(Priority::class)],
];
}
public function toData(): StoreTaskData
{
return new StoreTaskData(
title: $this->validated('title'),
dueAt: $this->date('due_at')?->toImmutable(),
priority: Priority::from($this->validated('priority')),
);
}
}
Watch the date. $this->date() returns a mutable Carbon unless the app calls Date::use(CarbonImmutable::class). The DTO asks for a CarbonImmutable, so convert it with toImmutable() before it gets there. The nullsafe ?-> handles an omitted due_at.
4. Data Objects (DTOs)
Skip spatie/laravel-data. A final readonly class with promoted constructor properties is enough — you get strong typing, immutability, and zero runtime overhead.
final readonly class StoreTaskData
{
public function __construct(
public string $title,
public ?CarbonImmutable $dueAt,
public Priority $priority,
) {}
public function toArray(): array
{
return [
'title' => $this->title,
'due_at' => $this->dueAt,
'priority' => $this->priority->value,
];
}
}
Rule: All communication between layers happens through Data objects. Never pass a bare
array $dataacross a boundary.
5. Actions
A single business operation per class. Dependency-injected, returns a model or value — not arrays.
final readonly class CreateTaskAction
{
public function __construct(
private RecordTaskCreatedAction $recordAuditTrail,
) {}
public function __invoke(StoreTaskData $data): Task
{
return DB::transaction(function () use ($data) {
$task = Task::create($data->toArray());
($this->recordAuditTrail)($task);
return $task;
});
}
}
An action’s entry point is either __invoke() or execute(). Invokable actions are called like a function — ($this->recordAuditTrail)($task). execute() actions are called by name — $this->recordAuditTrail->execute($task). Neither is wrong. Match whichever the codebase already uses, and don’t mix them.
Action conventions:
final readonly class {Verb}{Domain}Action- A single entry point:
__invoke()orexecute(), consistently across the codebase - Wrap multi-write operations in
DB::transaction() - Compose with other actions via constructor injection — never
app()orresolve()inside the body - Guard preconditions early; throw domain exceptions, don’t return error tuples
Rule: One action = one user story. If the name doesn’t describe a thing a stakeholder might ask for, it’s the wrong shape.
6. Models Are Dumb
Models hold relationships, casts, and accessors — that’s it. No saving, no validation, no orchestration. If logic depends on more than one model or sends a notification, it belongs in an Action.
final class Task extends Model
{
protected $casts = [
'priority' => Priority::class,
'status' => TaskStatus::class,
'due_at' => 'immutable_datetime',
];
public function owner(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
Prefer ULIDs over auto-increment IDs — they’re sortable, URL-safe, and don’t leak record counts.
7. Responses via Responsable
Skip ViewModels. For APIs, return Responsable classes that handle the JSON shape consistently.
final readonly class JsonDataResponse implements Responsable
{
public function __construct(
private mixed $data,
private int $status = 200,
) {}
public function toResponse($request): JsonResponse
{
return new JsonResponse(['data' => $this->data], $this->status);
}
}
Pair with JsonErrorResponse so error envelopes stay predictable. For HTML, return Blade views from the controller — they’re simple enough that an extra abstraction is pure cost.
8. State via Enums + Guards
Don’t reach for spatie/laravel-model-states. A backed enum and a guard in the relevant action handle 90% of cases:
enum TaskStatus: string
{
case Draft = 'draft';
case Active = 'active';
case Completed = 'completed';
public function canTransitionTo(self $next): bool
{
return match ($this) {
self::Draft => $next === self::Active,
self::Active => $next === self::Completed,
self::Completed => false,
};
}
}
final readonly class CompleteTaskAction
{
public function __invoke(Task $task): Task
{
throw_unless(
$task->status->canTransitionTo(TaskStatus::Completed),
new InvalidStateTransition("Task {$task->id} cannot be completed from {$task->status->value}"),
);
$task->update(['status' => TaskStatus::Completed]);
return $task;
}
}
If transitions get complex (side effects per transition, audit trails, parallel states), then reach for spatie/laravel-model-states — not before. The signal is a transition graph that no longer fits in a match.
9. CQRS, Lightly
Strict CQRS is overkill for most CRUD apps. Split at the controller level instead:
IndexController,ShowController— readsStoreController,UpdateController,DestroyController— writes
Reads can hit the model/query builder directly. Writes always go through an Action.
Rule: A controller either reads or writes. Never both.
4. PHP Style
These aren’t nice-to-haves — turn them on at the linter level:
declare(strict_types=1);at the top of every filefinal readonly classby default (dropreadonlyonly when you genuinely need mutation)- Constructor property promotion, always
- Return types and parameter types on every method — no exceptions
- PSR-12 formatting
matchinstead of nested ternaries or chainedif/elseif- Never call
app(),resolve(),Container::make(), or facade roots inside a Domain class — always inject - Models use ULIDs
5. Boundaries Between Domains
- Cross-domain calls go through Actions, not raw model relationships
- A domain may expose a few public Actions; everything else (private helpers, internal models) stays inside the namespace
- Avoid foreign keys across “important” boundaries (billing → CRM, for example) — bridge with IDs and an explicit lookup, so each side can move independently
- Domain Actions can call other domains’ Actions, but never
use Domain\Other\Models\...directly — go through the Action seam
6. Batches for Large Datasets
Sooner or later something has to touch every row in a big table — recalculating scores, backfilling a column, re-syncing with a vendor. That work belongs in src/Domain/<Domain>/Batches/. Don’t put it in a console command, an Action, or an ad-hoc job. Name it {Verb}{Domain}Batch so it sits in the domain’s vocabulary next to its Actions.
A Batch is a single Batchable job that processes one page, then appends a job for the next page to the batch it’s running in. It drains the table one page at a time and stops when a page comes back empty.
namespace Domain\Customer\Batches;
use Domain\Customer\Actions\RecalculateCustomerScoreAction;
use Domain\Customer\Models\Customer;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
final class RecalculateCustomerScoresBatch implements ShouldQueue
{
use Batchable;
public function __construct(
public readonly int $lastId = 0,
) {}
public function handle(RecalculateCustomerScoreAction $recalculateScore): void
{
if ($this->batch()?->cancelled()) {
return;
}
$customers = Customer::query()
->forPageAfterId(perPage: 100, lastId: $this->lastId)
->get();
$customers->each(fn (Customer $customer) => $recalculateScore($customer));
if ($customers->isNotEmpty()) {
$this->batch()->add(new self($customers->last()->id));
}
}
}
There are two choices in that class.
- Keyset pagination, never
OFFSET.forPageAfterIdasks for “the next 100 after this id”, which is an index seek no matter how deep you are.OFFSET 900000makes the database read and discard 900,000 rows first, so every page is slower than the one before it. And if rows are inserted or deleted while the walk is running, offset pages shift and skip or repeat records. - One job in flight, appending the next. Dispatching a job per page up front means counting the table and filling the queue before any work happens. A self-appending job stays inside one batch, so you still get progress,
then/catchcallbacks and cancellation. It also only ever has one page queued.
The Batch walks the dataset. The per-record business logic still lives in an Action the Batch invokes — here RecalculateCustomerScoreAction, injected into handle(). Keep the loop body thin.
Console commands and scheduled tasks dispatch the Batch and return immediately — they never run the query themselves:
Bus::batch([new RecalculateCustomerScoresBatch])
->name('recalculate-customer-scores')
->dispatch();
A command that only dispatches stays fast however big the table gets, and because each page is its own queued job, a deploy halfway through only interrupts one page rather than the whole walk. Queue-level details are their own topic: batch callbacks, cancellation, and keeping retry_after longer than a job’s timeout.
7. Vendor Integrations
Stripe, Twilio, Mailgun and S3 wrappers live in src/Support/<VendorName>/, one folder per vendor: src/Support/Stripe/, src/Support/Twilio/. Never a catch-all src/Support/Integrations/, and never inside src/Domain/ — a vendor has no business vocabulary of its own.
The split is contract in the domain, implementation in the vendor folder:
- The Domain owns the interface. Actions type-hint the contract, never the vendor SDK class.
src/Support/<VendorName>/classes hold no business logic — only translation between the vendor’s shape and the app’s Data objects.- A service provider binds the adapter to the contract, so swapping Stripe for Braintree touches no Domain code.
- Vendor config (API keys, webhook secrets) stays in
config/services.phpand arrives through the constructor — neverenv()insidesrc/Support/.
// src/Domain/Billing/Contracts/PaymentGateway.php
namespace Domain\Billing\Contracts;
interface PaymentGateway
{
public function charge(int $amountInCents, string $customerId): PaymentResult;
}
// src/Support/Stripe/StripePaymentGateway.php
namespace Support\Stripe;
final readonly class StripePaymentGateway implements PaymentGateway
{
public function __construct(
private StripeClient $client,
) {}
public function charge(int $amountInCents, string $customerId): PaymentResult
{
$charge = $this->client->charges->create([
'amount' => $amountInCents,
'customer' => $customerId,
'currency' => 'usd',
]);
return new PaymentResult(
successful: $charge->status === 'succeeded',
reference: $charge->id,
);
}
}
// AppServiceProvider::register()
$this->app->bind(StripeClient::class, fn () => new StripeClient(config('services.stripe.secret')));
$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);
src/Support/Stripe/
├── StripePaymentGateway.php
└── StripeWebhookVerifier.php
src/Support/Twilio/
└── TwilioSmsGateway.php
There’s a testing payoff too. An Action that takes a PaymentGateway can be handed a fake in a test, with no HTTP mocking and no Stripe test keys.
8. Naming Reference
| Type | Pattern | Example |
|---|---|---|
| Action | {Verb}{Domain}Action |
CreateTaskAction |
| Batch | {Verb}{Domain}Batch |
RecalculateTaskScoresBatch |
| Controller | {Verb}{Domain}Controller |
StoreTaskController |
| Request | {Verb}{Domain}Request |
StoreTaskRequest |
| Data | {Verb}{Domain}Data |
StoreTaskData |
| Response | {Shape}Response |
JsonDataResponse, JsonErrorResponse |
| Enum | {Concept}{Suffix} |
TaskStatus, Priority |
| Exception | {Problem}Exception |
InvalidStateTransition |
| Vendor adapter | {Vendor}{Contract} |
StripePaymentGateway |
9. Example Domain Layout
src/Domain/Task/
├── Actions/
│ ├── CreateTaskAction.php
│ ├── CompleteTaskAction.php
│ └── RecordTaskCreatedAction.php
├── Data/
│ └── StoreTaskData.php
├── Models/
│ └── Task.php
├── Enums/
│ ├── TaskStatus.php
│ └── Priority.php
├── Batches/
│ └── RecalculateTaskScoresBatch.php
└── Exceptions/
└── InvalidStateTransition.php
app/Http/
├── Controllers/Task/V1/
│ ├── IndexTaskController.php
│ ├── ShowTaskController.php
│ └── StoreTaskController.php
├── Requests/Task/V1/
│ └── StoreTaskRequest.php
└── Responses/
├── JsonDataResponse.php
└── JsonErrorResponse.php
Namespaces:
Domain\Task\Actions\CreateTaskActionDomain\Task\Data\StoreTaskDataApp\Http\Controllers\Task\V1\StoreTaskController
10. Pre-Ship Checklist
- Every business operation lives in an Action
- Controllers do nothing but wire Request → Action → Response
- No
array $datacrossing a boundary — Data objects everywhere - Form Requests carry validation and build the Data object via
toData() - Models contain no business logic
-
declare(strict_types=1)on every file - Every class is
final(andreadonlywhere mutation isn’t required) - No
app()/resolve()calls inside classes — DI everywhere - State transitions are gated by enum guards or explicit Actions
- Large-dataset walks live in
Batches/as self-appendingBatchablejobs, never in console commands - Vendor SDKs are wrapped in
src/Support/<VendorName>/, never called directly from a Domain - Tests target Actions and HTTP endpoints, not models