sinmiloluwa / laravel-dto-mapper
Elegant, type-safe DTO mapping for Laravel models and arrays.
v1.0.3
2025-10-18 08:36 UTC
Requires
- php: ^8.1
- illuminate/support: ^10.0|^11.0
Requires (Dev)
- orchestra/testbench: ^8.18
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
๐งฉ Elegant, type-safe DTO mapping for Laravel models and arrays.
๐ Features
- โ Map Eloquent models or arrays to typed DTOs
- ๐ฏ Supports PHP 8+ attributes (
#[MapFrom],#[Cast]) - ๐ง Automatic type casting (
int,bool,float,string) - โก Zero configuration โ drop it in and use
- ๐ก๏ธ Clear errors for missing or null values instead of silent defaults
๐ฆ Installation
composer require sinmiloluwa/laravel-dto-mapper
Requires PHP 8.1+ and Laravel 10 or 11.
๐ ๏ธ Usage
Add the MapsAttributes trait to a class with public typed properties, then call from() with an array, an Eloquent model or any object:
use App\Models\User; use Sinmiloluwa\LaravelDtoMapper\Attributes\Cast; use Sinmiloluwa\LaravelDtoMapper\Attributes\MapFrom; use Sinmiloluwa\LaravelDtoMapper\Traits\MapsAttributes; #[MapFrom(User::class)] class UserData { use MapsAttributes; public string $name; public ?string $nickname; public string $role = 'member'; #[Cast('int')] public int $age; #[Cast('bool')] public bool $active; } $dto = UserData::from(User::find(1)); $dto = UserData::from(['name' => 'Jane', 'age' => '25', 'active' => '1']); $dto->toArray(); // ['name' => 'Jane', 'nickname' => null, 'role' => 'member', 'age' => 25, 'active' => true]
Each public, non-static property is filled from the source key with the same name.
#[Cast]
Converts the value before it is assigned. The supported types are int, float, bool and string. A null value is never cast.
#[MapFrom]
Declares which class the DTO is built from. Passing an object of any other class throws a DtoMappingException. Arrays are always accepted.
Missing and null values
| Source value | Property | Result |
|---|---|---|
| key missing | has a default (= 'member') |
default is kept |
key missing or null |
nullable (?string) |
null |
key missing or null |
not nullable | DtoMappingException |
use Sinmiloluwa\LaravelDtoMapper\Exceptions\DtoMappingException; try { UserData::from(['age' => 30]); } catch (DtoMappingException $e) { // Property [name] on [UserData] is missing from the source and is not nullable. }
๐งช Testing
composer install vendor/bin/phpunit
๐ License
MIT. See LICENSE.