Data-Transfer Objects (DTOs)
Think of a DTO as nothing more (and nothing less) than a type-safe envelope for moving data between layers of your application.
Request --> DTO --> Service Layer --> Repository / Domain
A DTO:
• Has only data, no business logic
• Is usually immutable (once created, you don’t mutate it)
• Provides type-hints & IDE autocompletion
• Makes contracts between layers explicit (“this service needs exactly these fields”)
Why bother inside Laravel?
Laravel already gives you arrays, Illuminate\Http\Request, Eloquent models, resources… So why add one more abstraction?
- Decouple HTTP from Domain
A FormRequest often contains far more than your service actually needs. With a DTO you strip it down to the essentials.
- Type Safety (especially with PHP 8.1
readonly properties).
- Self-documenting code – your service signature becomes crystal-clear.
- Easier testing – you can construct the DTO directly without booting the whole HTTP kernel.
- Prevent leaking models to queues / events (serialisation headaches disappear).
Three common ways to implement DTOs in Laravel
| Approach | Pros | Cons |
|---|
1. Plain PHP class (readonly props) | Zero dependencies, full control | Manual validation / casting |
| 2. spatie/data-transfer-object | Small, battle-tested, casts & validation helpers | External package |
| 3. spatie/laravel-data | Deep Laravel integration, validation, transformation, JSON resources | Slightly heavier, learning curve |
1. Plain-Vanilla DTO
<?php
namespace App\DTO;
use Illuminate\Http\Request;
final readonly class CreatePostData
{
public function __construct(
public string $title,
public string $body,
public int $authorId,
) {}
// convenience factory
public static function fromRequest(Request $request): self
{
return new self(
title : $request->string('title'),
body : $request->string('body'),
authorId : $request->user()->id,
);
}
}
Using it in a controller
public function store(PostRequest $request, CreatePostService $service)
{
$dto = CreatePostData::fromRequest($request);
$post = $service->handle($dto);
return PostResource::make($post);
}
CreatePostService knows nothing about HTTP:
class CreatePostService
{
public function __construct(private PostRepository $repo) {}
public function handle(CreatePostData $data): Post
{
return $this->repo->create($data->title, $data->body, $data->authorId);
}
}
2. With spatie/data-transfer-object
composer require spatie/data-transfer-object
use Spatie\DataTransferObject\DataTransferObject;
class CreatePostData extends DataTransferObject
{
public string $title;
public string $body;
public int $authorId;
}
Spatie’s DTO is already immutable. Pass an array and it handles type-casting:
$dto = new CreatePostData(
title: $request->title,
body: $request->body,
authorId: $request->user()->id,
);
3. With spatie/laravel-data (richest option)
composer require spatie/laravel-data
php artisan vendor:publish --provider="Spatie\LaravelData\LaravelDataServiceProvider"
use Spatie\LaravelData\Data;
class CreatePostData extends Data
{
public function __construct(
public string $title,
public string $body,
#[DataCollectionOf(ImageData::class)]
public ?array $images,
) {}
}
Features:
• Validation rules right in the DTO
• Automatic casting to Eloquent models / enums
• Acts as JSON resource (->toResponse())
• Works in commands, events, jobs.
Practical workflow inside Laravel
- Validate → use FormRequest or built-in validation of
laravel-data.
- Map → convert to DTO (
CreatePostData::from(...)).
- Act → pass DTO to service / action / job.
- Return → optionally convert domain model to a “response DTO” (can reuse
laravel-data).
routes/web.php
└── Controller
├── FormRequest (validators)
├── **DTO**
├── Service / Action
└── Repository / Model
Dos & Don’ts
✔ DO make DTOs readonly / immutable.
✔ DO add simple factory helpers (fromRequest(), fromArray()).
✔ DO keep them free of business logic – it belongs to services or models.
✔ DO use them in Jobs, Events, Listeners to avoid serialising models.
✖ DON’T turn a DTO into an ActiveRecord clone – that defeats its purpose.
✖ DON’T pass raw Request or arrays deep into your domain once you adopt DTOs.
TL;DR
• A DTO is a light, typed container for data.
• Laravel plays nicely with DTOs—just sandwich one between the HTTP layer and your business layer.
• Implement it by hand for simple cases, or use Spatie’s packages for casting & validation sugar.
• The payoff is cleaner, more testable, and IDE-friendly code. Happy crafting! 🚀