โœ…
Laravel Validated DTO
View on GitHub
  • โœ…Validated DTO for Laravel
  • ๐Ÿš€Getting Started
    • Installation
    • Configuration
    • Upgrade Guide
    • Changelog
  • ๐Ÿ˜ŽThe Basics
    • Generating DTOs
    • Defining DTO Properties
    • Defining Validation Rules
    • Creating DTO Instances
    • Accessing DTO Data
    • Defining Default Values
    • Transforming DTO Data
    • Mapping DTO properties
    • Simple DTOs
    • Resource DTOs
    • Wireable DTOs
    • Lazy Validation
    • Generating TypeScript Definitions
  • ๐ŸŽจCustomize
    • Custom Error Messages and Attributes
    • Custom Exceptions
  • ๐ŸงชType Casting
    • Introduction
    • Available Types
    • Create Your Own Type Cast
    • Casting Eloquent Model properties to DTOs
Powered by GitBook
On this page
  • To array
  • To JSON string
  • To Eloquent Model
  • Custom transforming
  • Transforming Nested Data

Was this helpful?

  1. The Basics

Transforming DTO Data

You can convert your DTO to some formats:

To array

$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B',
]);

$dto->toArray();
// [
//     "name" => "John Doe",
//     "email" => "john.doe@example.com",
//     "password" => "s3CreT!@1a2B",
// ]

To JSON string

$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B',
]);

$dto->toJson();
// '{"name":"John Doe","email":"john.doe@example.com","password":"s3CreT!@1a2B"}'

$dto->toPrettyJson(); // OR LIKE THIS
// {
//     "name": "John Doe",
//     "email": "john.doe@example.com",
//     "password": "s3CreT!@1a2B"
// }

To Eloquent Model

$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B',
]);

$dto->toModel(\App\Models\User::class);
// App\Models\User {#3776
//     name: "John Doe",
//     email: "john.doe@example.com",
//     password: "s3CreT!@1a2B",
// }

Custom transforming

If you want to build your own Data Transformer, you can use the buildDataForExport() method to retrieve the validated data with your custom mappings.

public function toObject(): object
{
    return (object) $this->buildDataForExport();
}

Transforming Nested Data

Be aware that when transforming the DTO, all the properties are also going to be transformed:

Scalar Data Type and Array properties will preserve their values.

stdClass properties will be transformed into arrays using type casting.

UnitEnum properties are going to be transformed into the case name.

BackedEnum properties are going to be transformed into the case value.

Carbon and CarbonImmutable properties are going to be transformed into strings using the ->toISOString() method.

Collection, Model and DTO properties will have their nested data transformed using the same logic as above.

PreviousDefining Default ValuesNextMapping DTO properties

Last updated 10 months ago

Was this helpful?

๐Ÿ˜Ž