# Transforming DTO Data

You can convert your DTO to some formats:

### To array

```php
$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

```php
$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

```php
$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.

```php
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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wendell-adriel.gitbook.io/laravel-validated-dto/basics/transforming-dto-data.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
