PHPackages                             php-collective/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. php-collective/laravel-dto

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

php-collective/laravel-dto
==========================

Laravel integration for php-collective/dto

0.1.4(2mo ago)10MITPHPPHP &gt;=8.2CI passing

Since Dec 16Pushed 2mo agoCompare

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

READMEChangelog (5)Dependencies (12)Versions (11)Used By (0)

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

[](#laravel-dto)

Laravel integration for [php-collective/dto](https://github.com/php-collective/dto).

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

[](#installation)

```
composer require php-collective/laravel-dto
```

The service provider will be auto-discovered.

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

[](#configuration)

Publish the config file:

```
php artisan vendor:publish --provider="PhpCollective\LaravelDto\DtoServiceProvider"
```

This creates `config/dto.php` with the following options:

```
return [
    'config_path' => config_path(),     // Where DTO config files are located
    'output_path' => app_path('Dto'),   // Where to generate DTOs
    'namespace' => 'App\\Dto',          // Namespace for generated DTOs
    'typescript_output_path' => resource_path('js/types'), // TypeScript output
    'jsonschema_output_path' => resource_path('schemas'),  // JSON Schema output
];
```

Usage
-----

[](#usage)

### 1. Initialize DTO configuration

[](#1-initialize-dto-configuration)

```
php artisan dto:init
```

This creates a `config/dto.php` file with a sample DTO definition (PHP format is the default). You can also use `--format=xml` or `--format=yaml`.

The generated config looks like:

```
use PhpCollective\Dto\Builder\Dto;
use PhpCollective\Dto\Builder\Field;
use PhpCollective\Dto\Builder\Schema;

return Schema::create()
    ->dto(Dto::create('User')->fields(
        Field::int('id'),
        Field::string('name'),
        Field::string('email')->nullable(),
    ))
    ->toArray();
```

### 2. Generate DTOs

[](#2-generate-dtos)

```
php artisan dto:generate
```

Options:

- `--dry-run` - Preview changes without writing files
- `-v` - Verbose output

### 3. Generate TypeScript interfaces

[](#3-generate-typescript-interfaces)

```
php artisan dto:typescript
php artisan dto:typescript --multiple-files --readonly
```

### 4. Generate JSON Schema

[](#4-generate-json-schema)

```
php artisan dto:jsonschema
php artisan dto:jsonschema --multiple-files
```

### 5. Use your DTOs

[](#5-use-your-dtos)

```
use App\Dto\UserDto;

$user = new UserDto([
    'id' => 1,
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

return response()->json($user->toArray());
```

Eloquent Integration
--------------------

[](#eloquent-integration)

### Attribute Casting

[](#attribute-casting)

```
use App\Dto\ProfileDto;
use App\Dto\TagDto;
use PhpCollective\LaravelDto\Eloquent\DtoCast;
use PhpCollective\LaravelDto\Eloquent\DtoCollectionCast;
use PhpCollective\LaravelDto\Eloquent\HasDtoCasts;

class User extends Model
{
    protected $casts = [
        'profile' => DtoCast::class . ':' . ProfileDto::class,
        'tags' => DtoCollectionCast::class . ':' . TagDto::class,
    ];
}

$user = User::firstOrFail();
$profile = $user->profile;       // ProfileDto instance
$tags = $user->tags;             // Collection|null
```

Or opt into automatic casts:

```
class User extends Model
{
    use HasDtoCasts;

    protected array $dtoCasts = [
        'profile' => ProfileDto::class,
        'tags' => [
            'class' => TagDto::class,
            'collection' => true,
        ],
    ];
}
```

### Model to DTO

[](#model-to-dto)

```
use App\Dto\UserDto;
use PhpCollective\LaravelDto\Eloquent\CreatesDtoFromModel;

class User extends Model
{
    use CreatesDtoFromModel;

    protected function getDtoClass(): ?string
    {
        return UserDto::class;
    }
}

$dto = $user->toDto();
```

You can also extend the base model:

```
use PhpCollective\LaravelDto\Eloquent\DtoModel;

class User extends DtoModel
{
    protected function getDtoClass(): ?string
    {
        return UserDto::class;
    }
}
```

### Mapping Helpers

[](#mapping-helpers)

```
use App\Dto\UserDto;
use PhpCollective\LaravelDto\Eloquent\DtoMapper;

$user = User::with('posts')->firstOrFail();
$dto = DtoMapper::fromModel($user, UserDto::class, relations: ['posts']);

$dtos = DtoMapper::fromCollection(User::query()->get(), UserDto::class);
$paginator = DtoMapper::fromPaginator(User::query()->paginate(), UserDto::class);
```

### API Resources

[](#api-resources)

```
use PhpCollective\LaravelDto\Http\DtoResource;

return new DtoResource($dto);
// or
return DtoResource::collection($dtos);
```

Request Integration
-------------------

[](#request-integration)

### DtoFormRequest

[](#dtoformrequest)

```
use PhpCollective\LaravelDto\Http\DtoFormRequest;

class StoreUserRequest extends DtoFormRequest
{
    protected string $dtoClass = UserDto::class;

    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
        ];
    }
}

// In controller:
public function store(StoreUserRequest $request): JsonResponse
{
    $dto = $request->toDto();
    // ...
}
```

### DtoResolver

[](#dtoresolver)

Register once (e.g. in `AppServiceProvider::boot()`):

```
use PhpCollective\LaravelDto\Http\DtoResolver;

DtoResolver::register();
```

Then inject DTOs directly:

```
public function store(UserDto $dto): JsonResponse
{
    // $dto is built from request data
}
```

Collections
-----------

[](#collections)

The service provider automatically registers Laravel's `Illuminate\Support\Collection` for DTO collection fields. Define collection fields with the `[]` suffix:

```
Field::array('roles', 'Role'),  // Role[] collection
Field::array('tags', 'string'), // string[] collection
```

After generating, collection fields use Laravel's `Collection` class with all its methods (`filter`, `map`, `pluck`, etc.).

Validation Bridge
-----------------

[](#validation-bridge)

Convert DTO validation rules to Laravel validation arrays with `DtoValidationRules::fromDto()`. Integrates directly with Form Requests. See [Usage Guide](docs/README.md#validation-bridge) for details.

Supported Config Formats
------------------------

[](#supported-config-formats)

The package supports multiple config file formats:

- `dto.php` - PHP format (default)
- `dto.xml` - XML format
- `dto.yml` / `dto.yaml` - YAML format
- `dto/` subdirectory with multiple files

License
-------

[](#license)

MIT

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance87

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Total

5

Last Release

63d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/39854?v=4)[Mark Scherer](/maintainers/dereuromark)[@dereuromark](https://github.com/dereuromark)

---

Top Contributors

[![dereuromark](https://avatars.githubusercontent.com/u/39854?v=4)](https://github.com/dereuromark "dereuromark (35 commits)")

---

Tags

laraveldata-transfer-objectdto

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[livewire/volt

An elegantly crafted functional API for Laravel Livewire.

4195.3M84](/packages/livewire-volt)

PHPackages © 2026

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