PHPackages                             cerbero/laravel-dto - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. cerbero/laravel-dto

ActiveLibrary

cerbero/laravel-dto
===================

Data Transfer Object (DTO) for Laravel

2.2.2(4y ago)5813.6k2MITPHPPHP ^7.3||^8.0

Since Apr 20Pushed 4y ago4 watchersCompare

[ Source](https://github.com/cerbero90/laravel-dto)[ Packagist](https://packagist.org/packages/cerbero/laravel-dto)[ Docs](https://github.com/cerbero/laravel-dto)[ Fund](https://paypal.me/AndreaMarcoSartori)[ RSS](/packages/cerbero-laravel-dto/feed)WikiDiscussions develop Synced 2d ago

READMEChangelogDependencies (12)Versions (9)Used By (0)

Laravel DTO
===========

[](#laravel-dto)

[![Author](https://camo.githubusercontent.com/fffbc89ca2742dccf8be167716e04b7125a913abae0da6a488131999dab8ca25/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d617574686f72266d6573736167653d6365726265726f393026636f6c6f723d353041424631266c6f676f3d74776974746572267374796c653d666c61742d737175617265)](https://twitter.com/cerbero90)[![PHP Version](https://camo.githubusercontent.com/50cf693a1652ed03106415ff64bc7ef4c0f261de71e810d8258262b3a9045807/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6365726265726f2f6c61726176656c2d64746f3f636f6c6f723d253233344635423933266c6f676f3d706870267374796c653d666c61742d737175617265)](https://www.php.net)[![Laravel Version](https://camo.githubusercontent.com/4c2e5da6aec07bd5538de60b57e9774042431d47e1f18b5d3434cde68853ca4a/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d6c61726176656c266d6573736167653d254532253839254135352e3626636f6c6f723d666632643230266c6f676f3d6c61726176656c267374796c653d666c61742d737175617265)](https://laravel.com)[![Octane Compatibility](https://camo.githubusercontent.com/2bab41dd2c082d2a58c113b9fdd1fa5e56faafbfabd83b9195bab7ef1484b9e1/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d6f6374616e65266d6573736167653d636f6d70617469626c6526636f6c6f723d666632643230266c6f676f3d6c61726176656c267374796c653d666c61742d737175617265)](https://github.com/laravel/octane)[![Build Status](https://camo.githubusercontent.com/014981d0f008844997c3d7a1bdeaa4f0ac526515fa5b2e32d625895588df263f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f6365726265726f39302f6c61726176656c2d64746f2f6275696c643f7374796c653d666c61742d737175617265266c6f676f3d676974687562)](https://github.com/cerbero90/laravel-dto/actions?query=workflow%3Abuild)[![Coverage Status](https://camo.githubusercontent.com/39c72b1eb8fa449c4e559a1fb1d2009f2cda499fbf0b9eb43e58090b75cafea2/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f6365726265726f39302f6c61726176656c2d64746f2e7376673f7374796c653d666c61742d737175617265266c6f676f3d7363727574696e697a6572)](https://scrutinizer-ci.com/g/cerbero90/laravel-dto/code-structure)[![Quality Score](https://camo.githubusercontent.com/d117d0b163976a55007d275b153d2494b30b64a97d2b026fb1a9a72e5e3e14c8/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6365726265726f39302f6c61726176656c2d64746f2e7376673f7374796c653d666c61742d737175617265266c6f676f3d7363727574696e697a6572)](https://scrutinizer-ci.com/g/cerbero90/laravel-dto)[![Latest Version](https://camo.githubusercontent.com/1a2d9ac72576f844e14374576ddc850cf3eb3ba8221ba832666fd8d1d9e7f1d0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6365726265726f2f6c61726176656c2d64746f2e7376673f6c6162656c3d76657273696f6e267374796c653d666c61742d737175617265)](https://packagist.org/packages/cerbero/laravel-dto)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![PSR-12](https://camo.githubusercontent.com/9ba5754b3504e97a10e2b2f84770a218e69e544e9de8943eceb0b67599c83c6c/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6162656c3d636f6d706c69616e6365266d6573736167653d5053522d313226636f6c6f723d626c7565267374796c653d666c61742d737175617265)](https://www.php-fig.org/psr/psr-12/)[![Total Downloads](https://camo.githubusercontent.com/52b9ad8ee1fafb207c072a4b0967ad50ca859f6c9f62bb4565ec345e44e5fcfd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6365726265726f2f6c61726176656c2d64746f2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/cerbero/laravel-dto)

Laravel DTO integrates [DTO](https://github.com/cerbero90/dto), a package inspired by [Lachlan Krautz](https://github.com/lachlankrautz)' excellent [data-transfer-object](https://github.com/rexlabsio/data-transfer-object), with the functionalities of Laravel.

A data transfer object (DTO) is an object that carries data between processes. DTO does not have any behaviour except for storage, retrieval, serialization and deserialization of its own data. DTOs are simple objects that should not contain any business logic but rather be used for transferring data.

Below are explained the advantages brought by this package in a Laravel application. In order to discover all the features of DTO, please refer to the [full DTO documentation](https://github.com/cerbero90/dto).

Install
-------

[](#install)

Via Composer:

```
composer require cerbero/laravel-dto
```

To customize some aspects of this package, the `config/dto.php` file can optionally be generated via:

```
php artisan vendor:publish --tag=dto
```

Usage
-----

[](#usage)

- [Generate DTOs](#generate-dtos)
- [Instantiate a DTO](#instantiate-a-dto)
- [Resolve a DTO](#resolve-a-dto)
- [Convert into DTO](#convert-into-dto)
- [Convert into array](#convert-into-array)
- [Listen to events](#listen-to-events)
- [Support for macros](#support-for-macros)
- [DTO debugging](#dto-debugging)

### Generate DTOs

[](#generate-dtos)

DTOs for Eloquent models can be automatically generated by running the following Artisan command:

```
php artisan make:dto App/User
```

The database table of the specified model is scanned to populate the DTO properties. Furthermore, if the model has relationships, a DTO is also generated for each related model. For example, if our `User` model looks like:

```
class User extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}
```

The DTOs `App\Dtos\UserData` and `App\Dtos\PostData` are generated like so:

```
use Cerbero\LaravelDto\Dto;
use Carbon\Carbon;

use const Cerbero\Dto\PARTIAL;
use const Cerbero\Dto\IGNORE_UNKNOWN_PROPERTIES;

/**
 * The data transfer object for the User model.
 *
 * @property int $id
 * @property string $name
 * @property Carbon $createdAt
 * @property Carbon $updatedAt
 * @property PostData[] $posts
 */
class UserData extends Dto
{
    /**
     * The default flags.
     *
     * @var int
     */
    protected static $defaultFlags = PARTIAL | IGNORE_UNKNOWN_PROPERTIES;
}

/**
 * The data transfer object for the Post model.
 *
 * @property int $id
 * @property string $content
 * @property int $userId
 * @property Carbon $createdAt
 * @property Carbon $updatedAt
 * @property UserData $user
 */
class PostData extends Dto
{
    /**
     * The default flags.
     *
     * @var int
     */
    protected static $defaultFlags = PARTIAL | IGNORE_UNKNOWN_PROPERTIES;
}
```

By default, DTOs are generated in the `Dtos` directory which is created where models are. For example the DTO for `App\User` is generated as `App\Dtos\UserData` and the DTO for `App\Users\User` is generated as `App\Users\Dtos\UserData`.

To change either the location or the suffix `Data` of generated DTOs, we can create a DTO qualifier by implementing the interface `DtoQualifierContract` and replace the default qualifier in `config/dto.php`. The example below qualifies a DTO in the directory of the model and adds the suffix `Dto`:

```
use Cerbero\LaravelDto\DtoQualifierContract;

class MyDtoQualifier implements DtoQualifierContract
{
    public function qualify(string $model): string
    {
        return $model . 'Dto';
    }
}

// in config/dto.php
return [
    'qualifier' => MyDtoQualifier::class,
];
```

Finally, if a model has already its own DTO generated, we can overwrite it with the option `--force` or `-f`:

```
php artisan make:dto App/User --force
```

### Instantiate a DTO

[](#instantiate-a-dto)

In addition to the [traditional ways to instantiate a DTO](https://github.com/cerbero90/dto#instantiate-a-dto), Laravel DTO provides handy methods to create a new instance of DTO from HTTP requests, Eloquent models or other common interfaces present in Laravel.

For example `UserData` can be instantiated from an HTTP request by calling the method `fromRequest()`:

```
use App\Dtos\UserData;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $dto = UserData::fromRequest($request);
    }
}
```

The request passed to the method `fromRequest()` is optional: if not provided, the current application request is used to instantiate `UserData`.

By default the flags [PARTIAL](https://github.com/cerbero90/dto#partial) and [IGNORE\_UNKNOWN\_PROPERTIES](https://github.com/cerbero90/dto#ignore_unknown_properties) are applied to the DTO when it is instantiated from a request. [Additional flags](https://github.com/cerbero90/dto#available-flags) can be passed as second parameter to further customize the behaviour of the DTO.

---

To instantiate a DTO from an Eloquent model, we can call the method `fromModel()`:

```
$user = new User(['name' => 'Phil']);

$dto = UserData::fromModel($user);
```

The flags [PARTIAL](https://github.com/cerbero90/dto#partial), [IGNORE\_UNKNOWN\_PROPERTIES](https://github.com/cerbero90/dto#ignore_unknown_properties) and [CAST\_PRIMITIVES](https://github.com/cerbero90/dto#cast_primitives) are applied to the DTO when it is instantiated from a model. [Additional flags](https://github.com/cerbero90/dto#available-flags) can be passed as second parameter.

---

Finally, the method `from()` instantiates a DTO from several interfaces (specific to Laravel or not), including:

- `Illuminate\Support\Enumerable`
- `Illuminate\Contracts\Support\Arrayable`
- `Illuminate\Contracts\Support\Jsonable`
- `JsonSerializable`
- `Traversable`
- any value that can be casted into an array

In this case no flags are applied by default, but they can still be passed as second parameter.

### Resolve a DTO

[](#resolve-a-dto)

As long as [PARTIAL](https://github.com/cerbero90/dto#partial) is set in the default flags of a DTO, such DTO can be automatically resolved by the Laravel IoC container with the data carried by the current application request:

```
use App\Dtos\UserData;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function store(UserData $dto)
    {
        // ...
    }
}
```

### Convert into DTO

[](#convert-into-dto)

Another way to get an instance of DTO from different objects is letting them use the trait `TurnsIntoDto` and call the method `toDto()`:

```
use Cerbero\LaravelDto\Traits\TurnsIntoDto;

class StoreUserRequest extends Request
{
    use TurnsIntoDto;
}

class User extends Model
{
    use TurnsIntoDto;

    protected $dtoClass = UserData::class;
}

class Example
{
    use TurnsIntoDto;

    protected function getDtoClass(): ?string
    {
        return $condition ? UserData::class : OtherDto::class;
    }
}

$dto = $request->toDto(UserData::class, MUTABLE);
$dto = $user->toDto(CAST_PRIMITIVES);
$dto = $example->toDto();
```

Classes using the trait can specify the DTO to turn into by:

- passing the DTO class name as first parameter of the method `toDto()`
- defining the property `$dtoClass`
- overriding the method `getDtoClass()` if custom logic is needed

Flags can optionally be passed as second parameter, or first parameter if the DTO class is already defined in the class using the trait. When models turn into DTOs, the flag [CAST\_PRIMITIVES](https://github.com/cerbero90/dto#cast_primitives) is added to help casting values if casts are not defined on the Eloquent models.

### Convert into array

[](#convert-into-array)

By default Laravel DTO registers a [value converter](https://github.com/cerbero90/dto#convert-into-array) for `Carbon` instances. When a DTO is converted into array, all its `Carbon` objects are turned into an atom string and then converted back into `Carbon` instances when a new DTO is instantiated:

```
$dto = UserData::make(['created_at' => '2000-01-01']);
$dto->createdAt; // Carbon instance
$data = $dto->toArray(); // ['created_at' => '2000-01-01T00:00:00+00:00']

$dto = UserData::make($data);
$dto->createdAt; // Carbon instance
```

Conversions can be added or removed in the `config/dto.php` file, specifically via the key `conversions`:

```
use Carbon\Carbon;
use Cerbero\LaravelDto\Manipulators\CarbonConverter;

return [
    'conversions' => [
        Carbon::class => CarbonConverter::class,
    ],
];
```

### Listen to events

[](#listen-to-events)

The only feature added by this package to [listeners](https://github.com/cerbero90/dto#listen-to-events) is the ability to resolve dependencies via the Laravel IoC container. Dependencies can be injected into listeners constructor to be automatically resolved.

Listeners can be added or removed in the `config/dto.php` file, specifically via the key `listeners`:

```
return [
    'listeners' => [
        UserData::class => UserDataListener::class,
    ],
];
```

### Define flags globally

[](#define-flags-globally)

Sometimes we may want all our DTOs to share the same [flags](https://github.com/cerbero90/dto#available-flags), an example might be the need to always work with mutable DTOs. An easy way to accomplish that is defining such flags in the `config/dto.php` file:

```
return [
    'flags' => MUTABLE,
];
```

### Support for macros

[](#support-for-macros)

In case we need to add functionalities to all DTOs, an option might be using macros. Please refer to the Laravel documentation to see an [example of how to register a macro](https://laravel.com/docs/collections#extending-collections).

### DTO debugging

[](#dto-debugging)

When using the helpers `dump()` or `dd()`, only DTOs data will be shown instead of all the underlying architecture that makes the package work:

```
dd($dto);

// only DTO data is shown:

App\Dtos\UserData {#3224
  +name: "Phil"
}
```

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Testing
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE\_OF\_CONDUCT](CODE_OF_CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Andrea Marco Sartori](https://twitter.com/cerbero90)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~65 days

Recently: every ~39 days

Total

7

Last Release

1821d ago

Major Versions

1.0.0 → 2.0.02020-11-07

PHP version history (2 changes)1.0.0PHP ^7.1

2.0.0PHP ^7.3||^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/596523?v=4)[Matteo Picciolini](/maintainers/cerbero)[@cerbero](https://github.com/cerbero)

---

Top Contributors

[![cerbero90](https://avatars.githubusercontent.com/u/5838106?v=4)](https://github.com/cerbero90 "cerbero90 (55 commits)")

---

Tags

dtodto-entity-mapperdto-generatordto-mapperlaravellaravel-dtolaraveldata-transfer-objectdto

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/cerbero-laravel-dto/health.svg)

```
[![Health](https://phpackages.com/badges/cerbero-laravel-dto/health.svg)](https://phpackages.com/packages/cerbero-laravel-dto)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

759569.4k13](/packages/wendelladriel-laravel-validated-dto)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
