Package

Yorcreative Laravel Argonaut Dto

Argonaut is a lightweight Data Transfer Object (DTO) package for Laravel that supports nested casting, recursive serialization, and validation out of the box. Ideal for service layers, APIs, and clean architecture workflows.

Package

yorcreative/laravel-argonaut-dto

View on GitHub →


Laravel Argonaut DTO

GitHub license GitHub stars GitHub Org's stars GitHub issues GitHub forks PHPUnit

Laravel Argonaut DTO is a lightweight, highly composable package for transforming arrays, objects, or collections into structured DTOs (Data Transfer Objects), with built-in support for:

  • 🧱 Deep nested transformation and casting
  • 🔁 Type-safe data conversion
  • ✅ Validation using Laravel’s validator
  • 🧠 Explicit attribute prioritization
  • 📦 Clean serialization (toArray, toJson)
  • ♻️ Consistent data shape enforcement across boundaries

📦 Installation

Install via Composer:

composer require yorcreative/laravel-argonaut-dto

🚀 Quick Start

1. Define a DTO

DTOs extend ArgonautDTO, and define your expected structure via public properties, casting rules, and validation.

class UserDTO extends ArgonautDTO
{
    public string $username;
    public string $email;

    protected array $casts = [
        'username' => 'string',
        'email' => 'string',
    ];

    public function rules(): array
    {
        return [
            'username' => ['required', 'string'],
            'email' => ['required', 'email'],
        ];
    }
}

This defines a strongly typed DTO with both validation rules and simple type casting.


2. Create an Assembler

Assemblers are responsible for mapping raw inputs (arrays or objects) into your DTOs.

class UserDTOAssembler extends ArgonautAssembler
{
    public static function toUserDTO(object $input): UserDTO
    {
        return new UserDTO([
            'username' => $input->display_name,
            'email' => $input->email,
        ]);
    }
}

Assembler method names must follow the format to<ClassName>, and are resolved automatically using class_basename.


3. Assemble a DTO

Use the assembler to transform raw data into structured, casted DTO instances.

$dto = UserDTOAssembler::assemble([
    'display_name' => 'jdoe',
    'email' => 'jdoe@example.com',
], UserDTO::class);

You can also batch transform arrays or collections:

UserDTOAssembler::fromArray($userArray, UserDTO::class);
UserDTOAssembler::fromCollection($userCollection, UserDTO::class);

🧪 Real-World Example: Product + Features + Reviews

This example demonstrates nested relationships and complex type casting in action.

ProductDTO with nested casting:

class ProductDTO extends ArgonautDTO
{
    public string $title;
    public array $features;
    public Collection $reviews;
    public ?UserDTO $user = null;

    protected array $casts = [
        'features' => [ProductFeatureDTO::class],
        'reviews' => Collection::class . ':' . ProductReviewDTO::class,
        'user' => UserDTO::class,
    ];

    public function rules(): array
    {
        return [
            'title' => ['required', 'string'],
            'reviews' => ['sometimes', 'required', 'collection', 'min:1'],
        ];
    }
}

ProductDTOAssembler mapping input structure:

class ProductDTOAssembler extends ArgonautAssembler
{
    public static function toProductDTO(object $input): ProductDTO
    {
        return new ProductDTO([
            'title' => $input->product_name,
            'user' => $input->user,
            'features' => $input->features ?? [],
            'reviews' => $input->reviews ?? [],
        ]);
    }

    public static function toProductFeatureDTO(object $input): ProductFeatureDTO
    {
        return new ProductFeatureDTO([
            'name' => $input->name ?? 'Unnamed Feature',
            'description' => $input->description ?? null,
        ]);
    }

    public static function toProductReviewDTO(object $input): ProductReviewDTO
    {
        return new ProductReviewDTO([
            'rating' => (int) ($input->rating ?? 0),
            'comment' => $input->comment ?? '',
        ]);
    }
}

🎯 DTOs with Prioritized Attributes and Custom Setters

ArgonautDTO allows you to prioritize the assignment of specific fields using $prioritizedAttributes, which is critical for cases where one field influences others.

class UserDTO extends ArgonautDTO
{
    public ?string $firstName = null;
    public ?string $lastName = null;
    public string $username;
    public string $email;
    public ?string $fullName = null;

    protected array $prioritizedAttributes = ['firstName', 'lastName'];

    protected array $casts = [
        'firstName' => 'string',
        'lastName' => 'string',
        'username' => 'string',
        'email' => 'string',
        'fullName' => 'string',
    ];

    public function setFirstName($value)
    {
        $this->firstName = $value;
        $this->fullName = $this->firstName . ' ' . $this->lastName;
    }

    public function setLastName($value)
    {
        $this->lastName = $value;
        $this->fullName = $this->firstName . ' ' . $this->lastName;
    }

    public function rules(): array
    {
        return [
            'firstName' => ['nullable', 'string', 'max:32'],
            'lastName' => ['nullable', 'string', 'max:32'],
            'username' => ['required', 'string', 'max:64'],
            'email' => ['required', 'email', 'max:255'],
        ];
    }
}

🔁 Casting Reference

Casting allows you to automatically transform values into other DTOs, Laravel Collections, arrays, dates, and more.

protected array $casts = [
    'registeredAt' => \Illuminate\Support\Carbon::class,
    'profile' => ProfileDTO::class,
    'roles' => [RoleDTO::class],
    'permissions' => Collection::class . ':' . PermissionDTO::class,
];
Cast Type Example Description
Scalar 'string', 'int', etc. Native PHP type cast
Single DTO ProfileDTO::class Cast an array to a DTO instance
Array of DTOs [RoleDTO::class] Cast to array of DTOs
Collection of DTOs Collection::class . ':' . CommentDTO::class Cast to a Laravel Collection
Date casting Carbon::class Cast to Carbon/DateTime instance

✅ Validation

Validate DTOs with Laravel’s validator:

$userDTO->validate();         // Throws ValidationException
$userDTO->validate(false);    // Returns array of errors (non-throwing)
$userDTO->isValid();          // Returns true/false

📤 Serialization

Serialize DTOs for output, API responses, etc.

$userDTO->toArray(); // Recursively converts nested DTOs
$userDTO->toJson();  // JSON output (throws on encoding errors)

🛠️ DTO Collection Helper

Create DTO collections directly:

UserDTO::collection([
    ['username' => 'john', 'email' => 'john@example.com'],
]);

🧪 Testing

Run the test suite using:

composer test

📚 Credits


📃 License

This package is open-sourced software licensed under the MIT license.

Yorcreative Laravel Argonaut Dto Related Articles

Argonaut DTO Package for Laravel image

Argonaut DTO Package for Laravel

Read article
Validated DTO Package for Laravel image

Validated DTO Package for Laravel

Read article
Data Transfer Object V3 Modernizes DTOs With PHP 8 Features image

Data Transfer Object V3 Modernizes DTOs With PHP 8 Features

Read article
Building your own Laravel Packages image

Building your own Laravel Packages

Read article
API Integrations using Saloon in Laravel image

API Integrations using Saloon in Laravel

Read article
Remove Sensitive Information from Laravel Apps image

Remove Sensitive Information from Laravel Apps

Read article

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm

Let your users buy domains without leaving your app

If your Laravel app gives users a site, a storefront, or a workspace, they’ll eventually want their own domain. The name.com API lets them search, register, and connect one without leaving your product. It’s a clean REST API, so Laravel’s HTTP client is all you need.

Let your users buy domains without leaving your app

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum