Data Transfer Object (DTO) in Laravel
Published: 2023-01-28 01:38:39

---
title: Data Transfer Object (DTO) in Laravel
published: true
description: Data Transfer Object (DTO) in Laravel, but not limited to Laravel. You can implement in any language. It will help make transparent your incoming data format, prevent you from making mistake, help to static analysis with Larastan
tags: 
# cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0odpflc29m2a1ocb66u.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-27 18:10 +0000
---


 ![Data Transfer Object (DTO) in Laravel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0odpflc29m2a1ocb66u.png)

We are using DTO in all Laravel projects at [Besnik](https://l.besnik.net/besnik).
 

#What is DTO?

DTO stands for "Data Transfer Object," and it is a design pattern that can be used to abstract the transfer of data between layers in a software application.

#Why DTO ?

DTO, short for Data Transfer Object, is a pattern that aims to simplify the flow of data between layers of a software application. It allows developers to abstract the data transfer process by creating a plain old object that holds the data and its structure, and this allows for better organization and maintainability of the code. DTOs can also be used for data validation, sanitation, and optimization.

Some reason why we must use DTO:

1. **Transparent definition of data:** DTO can help ensure that data is properly typed, by explicitly defining the data types for each property. This allows for stronger type checking and can prevent errors that might occur when using loosely typed data. Additionally, DTOs provide a structured way of accessing data, by exposing it through object properties, rather than anonymous properties, making the code more readable and easier to understand.

2. **Mistake-Free**: DTO can help prevent mistakes in a software application by providing a clear reference to the data being transferred. When accessing data from a request object or remote request response, it can be easy to make mistakes as there is no clear reference to the data being used. However, with a DTO, all data is referenced through the properties of the DTO object. This makes it easier to see and understand the data being used, and can also prevent mistakes as the IDE will prompt the developer to use the correct properties. Additionally, DTO can also provide validation and sanitation methods to further reduce the chance of errors.

3. **Clean Code:** We can maintain clean code. Other developer can easily understand that which data we need to receive. 

4. **Enhancing security:** With PHP type hinting, we can validate data when assigning to DTO object.

5. **Improving performance:** DTO can be used to optimize data transfer by only transferring the necessary data. This can improve the performance of the application, especially when dealing with large amounts of data.
 
6. **Testability:** DTO can be used to isolate the data layer of an application, allowing it to be tested independently of the business logic. Additionally, by using DTO, the data layer can be subject to static analysis to identify potential issues or bugs before the application is run. This can improve the overall quality and reliability of the code.

Overall, DTO can improve the organization and clarity of the code, making it easier to understand and maintain.

#How we Implement ?


####First Way (Old Way)

```php
use Illuminate\Http\Request;

class TestDto
{
    public $name;
    public $email;

    public function __construct($name, $email)
    {
        $this->name = $name;
        $this->email = $email;
    }

    public function fromRequest(Request $request)
    {
        return new self(
            $request->input('name'),
            $request->input('email'),
        );
    }
}
```



####Second Way


```php
use Illuminate\Http\Request;

class TestDto
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly string|null $address,
    ) {}

    public function fromRequest(Request $request): TestDto
    {
        return new self(
            $request->input('name'),
            $request->input('email'),
            $request->input('address'),
        );
    }
}
```


####Third Way

```php
use Illuminate\Http\Request;

class TestDto
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly string|null $address,
    ) {
        $this->validate();
    }

    public function fromRequest(Request $request): TestDto
    {
        return new self(
            $request->input('name'),
            $request->input('email'),
            $request->input('address'),
        );
    }

    public function validate()
    {
    }
}
```

####Forth way

You can use a nice package from [@wendell_adriel](https://twitter.com/wendell_adriel). 

##[Data Transfer Objects with validation for Laravel applications](https://github.com/WendellAdriel/laravel-validated-dto)


Thank you for your time to read the article.

###You can Follow me on [Twitter](https://twitter.com/ALEMRANCU)

Our Products:

##[Ezytor.com](https://l.besnik.net/ezytor)

##[Flowgiri.com](https://l.besnik.net/flowgiri)

##[Uihut.com](https://l.besnik.net/uihut) 

##[Graphicsly.net](https://l.besnik.net/graphicsly-em)