> For the complete documentation index, see [llms.txt](https://docs.opensoutheners.com/oss/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.opensoutheners.com/oss/laravel-data-mapper/3.x/usage.md).

# Usage

Data transfer objects are useful to pass data, they can be used everywhere but has some special uses in multiple places like controllers (including their route bindings) and queued jobs.

## Usage as standalone

{% hint style="warning" %}
Remember that using the constructor like `new CreatePostData` is also a valid option but it will not map all the data.
{% endhint %}

You can use DTOs on every place you want as the following:

```php
$data = CreatePostData::fromArray([
    'title' => 'Hello world',
    'content' => 'hello world',
    'tags' => '1,3'
]);
```

## Usage in controllers

Now at the controller level you may do something like the following:

```php
// PostController.php

public function store(CreatePostFormRequest $request)
{
    $post = $this->repository->create(
        CreatePostData::fromRequest($request)
    );
    
    // Response here...
}
```

This can be also be shorter by injecting directly the DTO like the following:

```php
// PostController.php

public function store(CreatePostData $data)
{
    $post = $this->repository->create($data);
    
    // Response here...
}
```

But then you might also think that your data must be validated, then you should read the following section.

### Validating request data

To be able to send a `FormRequest` that will also run validation inside the DTO you may need to create a `ValidatedDataTransferObject`.&#x20;

The best way to do so is by running the following command:

```bash
php artisan make:dto PostCreateData --request
```

You can also specify the `FormRequest` class path so it will be injected directly:

{% hint style="info" %}
This way will try reading validation rules array from the `FormRequest` then add them as properties to the DTO class with their types and, if nullable, adding default value as null.
{% endhint %}

```bash
php artisan make:dto PostCreateData --request="App\\Http\\Requests\\PostCreateFormRequest"
```

This way you will have something like the following:

```php
<?php

namespace App\DataTransferObjects;

use OpenSoutheners\LaravelDto\DataTransferObject;
use OpenSoutheners\LaravelDto\Contracts\ValidatedDataTransferObject;
use App\Http\Requests\PostCreateFormRequest;

final class PostCreateData extends DataTransferObject implements ValidatedDataTransferObject
{
    public function __construct(
        // You may have some properties here if your FormRequest rules contains anything...
    ) {
        //
    }
    
    /**
     * Get form request that this data transfer object is based from.
     */
    public static function request(): string
    {
        return PostCreateFormRequest::class;
    }
}
```

Now whenever you use this DTO on your controllers sending your `FormRequest` instance or [injecting it directly in your controller methods](#usage-in-controllers) will run validation on the data provided.

## Usage in queued jobs

The usage on queued jobs is automatically performed by the package itself, it will serialise and deserialise all the data from the DTO when the queued job enters to the queues processor.

Just adding an example to clarify its usage, having the following queued job:

```php
<?php
 
namespace App\Jobs;

use App\DataTransferObjects\PostCreateData;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
 
class ProcessPostCreation implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(protected PostCreateData $data)
    {
        //
    }
 
    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $this->data->post; // This will get the post model instance
    }    
}
```

Then sending this job to the queue with the data transfer object already created using `fromArray` or `fromRequest` methods or via controller binding:

```php
// Somewhere in your application...
use App\DataTransferObjects\PostCreateData;
use App\Jobs\ProcessPostCreation;

dispatch(
    new ProcessPostCreation(
        PostCreateData::fromArray([
            'title' => 'Hello World',
            'content' => 'Lorem ipsum...',
            'tags' => '1,5,8',
        ])
    )
);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.opensoutheners.com/oss/laravel-data-mapper/3.x/usage.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
