PHPackages                             afonsoogomes/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. [Utility &amp; Helpers](/categories/utility)
4. /
5. afonsoogomes/laravel-dto

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

afonsoogomes/laravel-dto
========================

A library for handling DTOs with Laravel.

1.0.2(1y ago)223MITPHPPHP ^7.3|^8.0

Since Jul 29Pushed 1y ago2 watchersCompare

[ Source](https://github.com/afonsoogomes/laravel-dto)[ Packagist](https://packagist.org/packages/afonsoogomes/laravel-dto)[ RSS](/packages/afonsoogomes-laravel-dto/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (10)Used By (0)

Laravel DTO Library
===================

[](#laravel-dto-library)

A Laravel library for creating and managing Data Transfer Objects (DTOs) with validation and an Artisan command for easy DTO generation.

Features
--------

[](#features)

- **DTO Class**: A base class for creating DTOs with validation.
- **Artisan Command**: A command to easily generate new DTO classes.

Installation
------------

[](#installation)

To install the library, add it to your `composer.json` file or run the following command:

```
composer require afonsoogomes/laravel-dto
```

Usage
-----

[](#usage)

### Creating a DTO Class

[](#creating-a-dto-class)

To create a new DTO class, use the provided Artisan command:

```
php artisan make:dto {name}
```

Replace `{name}` with the desired name for your DTO class. The command will generate a new DTO class in the `app/DTO` directory.

### Example DTO Class

[](#example-dto-class)

Here's an example of how to use the `DTO` class:

```
namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class UserDTO extends DTO
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $email;

    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email'],
        ];
    }
}
```

### Using the DTO

[](#using-the-dto)

You can create an instance of the DTO and access its properties like so:

```
$userDTO = UserDTO::make([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
]);

echo $userDTO->name;  // John Doe
```

### Advanced Examples

[](#advanced-examples)

#### Using `defaults`

[](#using-defaults)

The `defaults` method allows you to define default values for the DTO fields. Here's an example:

```
namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class ProductDTO extends DTO
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var float
     */
    public $price;

    /**
     * @var integer
     */
    public $stock;

    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'price' => ['required', 'numeric'],
            'stock' => ['required', 'integer'],
        ];
    }

    protected function defaults(): array
    {
        return [
            'stock' => 0, // Default stock value
        ];
    }
}

// Using the DTO with default values

$data = [
    'name' => 'Product Name',
    'price' => 19.99,
];

$productDTO = ProductDTO::make($data);

echo $productDTO->name;  // Product Name
echo $productDTO->price; // 19.99
echo $productDTO->stock; // 0 (default value)
```

#### Using `transform`

[](#using-transform)

The `transform` method allows you to process data before validation. For example, to clean up a phone number:

```
namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class UserDTO extends DTO
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $email;

    /**
     * @var string
     */
    public $phone;

    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email'],
            'phone' => ['required', 'string', 'size:10'],  // Example: must be 10 digits
        ];
    }

    protected function transform(): array
    {
        return [
            'phone' => preg_replace('/\D/', '', $this->phone) // Remove non-numeric characters from phone
        ];
    }
}

// Using the DTO with data transformation

$data = [
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'phone' => '(123) 456-7890', // Original format
];

$userDTO = UserDTO::make($data);

echo $userDTO->name;   // John Doe
echo $userDTO->email;  // john.doe@example.com
echo $userDTO->phone;  // 1234567890 (transformed to 10 digits)
```

#### Combined Example

[](#combined-example)

Here is an example that uses both `defaults` and `transform`:

```
namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class OrderDTO extends DTO
{
    /**
     * @var string
     */
    public $order_id;

    /**
     * @var float
     */
    public $amount;

    /**
     * @var string
     */
    public $currency;

    protected function rules(): array
    {
        return [
            'order_id' => ['required', 'string'],
            'amount' => ['required', 'numeric'],
            'currency' => ['required', 'string', 'size:3'], // Example: 3-letter currency code
        ];
    }

    protected function defaults(): array
    {
        return [
            'currency' => 'USD', // Default currency value
        ];
    }

    protected function transform(): array
    {
        return [
            'order_id' => strtoupper($this->order_id), // Transform order ID to uppercase
        ];
    }
}

// Using the DTO with default values and data transformation

$data = [
    'order_id' => 'abc123',
    'amount' => 99.99,
];

$orderDTO = OrderDTO::make($data);

echo $orderDTO->order_id; // ABC123 (transformed to uppercase)
echo $orderDTO->amount;   // 99.99
echo $orderDTO->currency; // USD (default value)
```

#### Whitelist

[](#whitelist)

The `whitelist` parameter allows you to restrict the DTO to only accept properties that are explicitly defined in the class. When set to `true`, any properties in the input data that are not defined as class properties will be ignored. Here's an example:

```
namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class OrderDTO extends DTO
{
    /**
     * @var string
     */
    public $order_id;

    /**
     * @var float
     */
    public $amount;

    /**
     * @var string
     */
    public $currency;

    protected function rules(): array
    {
        return [
            'order_id' => ['required', 'string'],
            'amount' => ['required', 'numeric'],
            'currency' => ['required', 'string', 'size:3'], // Example: 3-letter currency code
        ];
    }

    protected function defaults(): array
    {
        return [
            'currency' => 'USD', // Default currency value
        ];
    }

    protected function transform(): array
    {
        return [
            'order_id' => strtoupper($this->order_id), // Transform order ID to uppercase
        ];
    }
}

// Using the DTO with default values and data transformation

$data = [
    'order_id' => 'abc123',
    'amount' => 99.99,
    'unknown_field' => 'this will be ignored'
];

// Whitelist is set to true as the second parameter
$orderDTO = OrderDTO::make($data, true);

// Only defined properties are set
echo $orderDTO->order_id;  // abc123
echo $orderDTO->amount; // 99.99
echo $orderDTO->unknown_field; // undefined
```

### Command Options

[](#command-options)

- `name`: The name of the DTO class to be created. You can use forward slashes to create nested directories.

Example:

```
php artisan make:dto UserProfileDTO
```

This will create a `UserProfileDTO.php` file in the `app/DTO` directory.

Configuration
-------------

[](#configuration)

### DTO Constructor

[](#dto-constructor)

The DTO constructor accepts the following parameter:

- `array $items`: The initial data for the DTO.

### Methods

[](#methods)

- `__construct(array $items = [])`: Constructor to initialize the DTO with data and perform validation.
- `rules()`: Method to define validation rules for the DTO. Override this method in your DTO classes.
- `messages()`: Get the validation error messages for the DTO.
- `transform()`: Method to preprocess the data before validation.
- `defaults()`: Method to define default values for the DTO.
- `get($key, $default = null)`: Method to get a value from the DTO by key.
- `only(array $keys)`: \* Get only the specified keys from the collection.
- `except(array $keys)`: Method to get all items in the collection except for those with the specified keys..
- `all()`: Method to get all the data in the DTO.
- `has(string $key)`: Method to check if a key exists in the DTO.
- `set(string $key, $value)`: Method to set a value in the DTO by key.
- `remove(string $key)`: Method to remove a value from the DTO by key.
- `count()`: Method to count the number of items in the DTO.
- `toArray()`: Method to convert the DTO to an array.
- `toJson()`: Method to convert the DTO to a JSON string.
- `make(array $data)`: Static method to create a new DTO instance from an array.

Testing
-------

[](#testing)

To test the library, make sure you have Laravel installed and configured. Create a new DTO class using the Artisan command and verify that it works as expected.

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

[](#contributing)

If you would like to contribute to the library, please submit a pull request on GitHub. Ensure that you follow the coding standards and include tests for new features.

License
-------

[](#license)

This library is licensed under the MIT License. See the [LICENSE](https://github.com/afonsoogomes/laravel-dto/blob/main/LICENSE.md) file for more information.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance41

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 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 ~21 days

Recently: every ~27 days

Total

9

Last Release

485d ago

Major Versions

0.0.6 → 1.0.02025-01-12

### Community

Maintainers

![](https://www.gravatar.com/avatar/c27f7d38e73623a531563e3de1c04d5941214acc0243f96098fe22ed73ab0fb7?d=identicon)[afonsooliveira](/maintainers/afonsooliveira)

---

Top Contributors

[![afonsoogomes](https://avatars.githubusercontent.com/u/37506445?v=4)](https://github.com/afonsoogomes "afonsoogomes (24 commits)")

### Embed Badge

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

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

###  Alternatives

[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)[wnx/laravel-stats

Get insights about your Laravel Project

1.8k1.8M7](/packages/wnx-laravel-stats)[orchestra/canvas

Code Generators for Laravel Applications and Packages

21017.2M158](/packages/orchestra-canvas)[pulkitjalan/ip-geolocation

IP Geolocation Wrapper with Laravel Support

89164.9k1](/packages/pulkitjalan-ip-geolocation)[aedart/athenaeum

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

255.2k](/packages/aedart-athenaeum)[interaction-design-foundation/laravel-geoip

Support for multiple Geographical Location services.

17221.0k3](/packages/interaction-design-foundation-laravel-geoip)

PHPackages © 2026

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