Creating DTO Instances

You can create a DTO instance on many ways:

From arrays

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

You can also use the fromArray static method:

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

From JSON strings

$dto = UserDTO::fromJson('{"name": "John Doe", "email": "john.doe@example.com", "password": "s3CreT!@1a2B"}');

From Request objects

public function store(Request $request): JsonResponse
{
    $dto = UserDTO::fromRequest($request);
}

Starting in v3, you can also use the DTO as it was a Form Request class, so instead of manually creating the DTO instance, you can type-hint the DTO in the controller method, and it will be automatically created for you:

From Eloquent Models

Beware that the fields in the $hidden property of the Model won't be used for the DTO.

From Artisan Commands

You have three ways of creating a DTO instance from an Artisan Command:

From the Command Arguments

From the Command Options

From the Command Arguments and Options

Last updated