Search by

sinmiloluwa / laravel-dto-mapper

Sinmi

Elegant, type-safe DTO mapping for Laravel models and arrays.

Package info

github.com/Sinmiloluwa/laravel-dto-mapper

pkg:composer/sinmiloluwa/laravel-dto-mapper

Statistics

Installs: 37

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.3 2025-10-18 08:36 UTC

This package is auto-updated.

Last update: 2026-09-23 16:18:21 UTC


README

Latest Version on Packagist Total Downloads Tests

๐Ÿงฉ 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.