mohamad-zatar / laravel-dto-tools
A set of tools to make working with Data Transfer Objects easier in Laravel
Package info
github.com/mohamad-zatar/laravel-dto-tools
pkg:composer/mohamad-zatar/laravel-dto-tools
Requires
- php: ^8.3
- eventsauce/object-hydrator: ^1.8
- illuminate/console: ^12.0|^13.0
- illuminate/contracts: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
Requires (Dev)
- laravel/pint: ^1.18
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^4.0
- phpstan/phpstan: ^2.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-03 21:14:36 UTC
README
Generate and hydrate plain, readonly Data Transfer Objects (DTOs) in Laravel. Your DTOs stay ordinary PHP classes: no base class to extend and no magic.
php artisan make:dtogenerates afinal readonlyclass.Hydrator::fill()turns an array, such as$request->validated(), into a typed DTO.fill()is typed with generics, so static analysis knows exactly which DTO you get back.- The generated class comes from a stub you can publish and customise.
Requirements
- PHP 8.3 or higher
- Laravel 12 or 13
Installation
composer require mohamad-zatar/laravel-dto-tools
The service provider and the Hydrator facade alias are registered automatically through Laravel's package discovery.
Generating DTOs
php artisan make:dto ProductData
This creates app/DataObjects/ProductData.php:
<?php declare(strict_types=1); namespace App\DataObjects; use MohamadZatar\DataObjects\Contracts\DataObjectContract; final readonly class ProductData implements DataObjectContract { public function __construct( // ) {} public function toArray(): array { return []; } }
The class is final readonly, so you do not have to declare each property as readonly. It implements
DataObjectContract, which requires a toArray() method so you can easily turn your DTOs back into arrays.
If the file already exists, the command stops so it does not overwrite your changes. Pass --force (or -f) to
overwrite it:
php artisan make:dto ProductData --force
Customising the stub
To change the class that make:dto generates, publish the stub to stubs/dto.stub in your application:
php artisan vendor:publish --tag=dto-stubs
The stub is also published when you run Laravel's php artisan stub:publish. Once stubs/dto.stub exists,
make:dto uses it instead of the package's default.
Hydrating DTOs
Add your properties to the constructor and fill in toArray():
final readonly class ProductData implements DataObjectContract { public function __construct( public string $name, public int $priceInCents, public ?string $description = null, ) {} public function toArray(): array { return [ 'name' => $this->name, 'price_in_cents' => $this->priceInCents, 'description' => $this->description, ]; } }
Then fill it from an array with the Hydrator facade:
use App\DataObjects\ProductData; use MohamadZatar\DataObjects\Facades\Hydrator; $product = Hydrator::fill( class: ProductData::class, properties: ['name' => 'Desk', 'price_in_cents' => 12900], ); $product->priceInCents; // 12900 $product->description; // null
Or inject HydratorContract through Laravel's container:
use App\DataObjects\ProductData; use App\Http\Requests\StoreProductRequest; use App\Models\Product; use MohamadZatar\DataObjects\Contracts\HydratorContract; final class StoreProductController { public function __construct( private readonly HydratorContract $hydrator, ) {} public function __invoke(StoreProductRequest $request) { $product = $this->hydrator->fill( class: ProductData::class, properties: $request->validated(), ); return Product::query()->create( attributes: $product->toArray(), ); } }
The facade resolves HydratorContract from the container, so if you bind your own implementation, both the facade
and injected instances use it.
How array keys map to properties
snake_casekeys map tocamelCaseproperties:price_in_centsfills$priceInCents.- Optional parameters fall back to their default value when the key is missing.
- A missing required key throws
EventSauce\ObjectHydrator\UnableToHydrateObject. ItsmissingFields()method lists the keys that were missing.
use EventSauce\ObjectHydrator\UnableToHydrateObject; try { Hydrator::fill(ProductData::class, ['name' => 'Desk']); } catch (UnableToHydrateObject $exception) { $exception->missingFields(); // ['price_in_cents'] }
Typed results
fill() is typed with generics, so PHPStan and IDEs that read generic docblocks know that
Hydrator::fill(class: ProductData::class, ...) returns a ProductData, not just a DataObjectContract.
Under the hood
Hydration is powered by EventSauce's Object Hydrator, created by Frank de Jonge. It is possibly the best package I have found to hydrate objects nicely in PHP. Its documentation covers casting, nested objects, enums and more if you need to go further.
Upgrading from 1.x
- Require PHP 8.3+ and Laravel 12 or 13.
make:dtonow always generates afinal readonlyclass.- The
Hydratorfacade resolvesHydratorContractinstead of the concreteHydrateclass. - If you copied the old README examples, rename the
parameters:argument toproperties:.
See the CHANGELOG for every change.
Testing
composer test # Pest test suite composer static # PHPStan (level 9), including the type tests in tests/Types composer check # Pint code style check
Changelog
See CHANGELOG.md.
License
The MIT License (MIT). Please see License File for more information.