PHPackages                             ccharz/laravel-dto-lite - 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. ccharz/laravel-dto-lite

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

ccharz/laravel-dto-lite
=======================

Simple Laravel Data Transfer Object

v3.9.0(3mo ago)02.4kMITPHPPHP ^8.2CI passing

Since Mar 29Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/ccharz/laravel-dto-lite)[ Packagist](https://packagist.org/packages/ccharz/laravel-dto-lite)[ RSS](/packages/ccharz-laravel-dto-lite/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (10)Versions (23)Used By (0)

Laravel Data Transfer Object Lite
=================================

[](#laravel-data-transfer-object-lite)

This is a basic implementation of the data transfer object (DTO) concept. The idea is to describe input and output of data in one simple basic php class file. It is meant to replace FormRequests and Resources and can also be used to automatically generate typescript definitions.

This package is similar to the [Laravel Data](https://spatie.be/docs/laravel-data) Package from Spatie. The main difference it contains no reflection class magic and only provides the basic functionalities.

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

[](#installation)

```
composer require ccharz/laravel-dto-lite
```

Usage
-----

[](#usage)

### Example DTO

[](#example-dto)

```
enum ContactType : string {
    case PERSON = 'person';
    case COMPANY = 'company';
}

readonly class ContactData extends DataTransferObject {
    public function __construct(
        public string $name,
        public string $email,
        public ContactType $type,
    ) {}
}
```

### Casts

[](#casts)

Casts for attributes can be defined similar to eloquent casts. It is also possible to define casts to an array

```
enum ContactType : string {
    case PERSON = 'person';
    case COMPANY = 'company';
}

readonly class AddressData extends DataTransferObject
{
    public function __construct(
        public ?string $country = null,
        public ?string $zip = null,
        public ?string $location = null,
        public ?string $street = null,
        public ?string $streetnumber = null,
        public ?string $stair = null,
        public ?string $top = null,
    ) {
    }
}

readonly class ContactData extends DataTransferObject {
    public function __construct(
        /** @var AddressData[] $addresses */
        public array $addresses,
        public DateTime $birthday,
        public ContactType $type,
    ) {}

    public static function casts(): array
    {
        return [
            'addresses' => AddressData::class . '[]',
            'birthday' => 'datetime',
            'type' =>  ContactType::class,
        ];
    }
}
```

### Validation

[](#validation)

If a rules method exists, validation is automatically performed when creating a DTO from a request manually or by automatic dependency injection.

```
use Illuminate\Http\Request;

public static function rules(?Request $request = null): ?array
{
    return ['prename' => 'min:2'];
}
```

You can also inject the rules from casts in your rules:

```
use Illuminate\Http\Request;

public static function rules(?Request $request = null): ?array
{
    return [
        ...parent::castRules(),
    ];
}
```

### Automatic Injection

[](#automatic-injection)

With the help if laravels dependency injection, the dto can be used in a controller method function and is automatically filled with the **validated** input data from the request.

```
public function store(ContactData $contactData): RedirectResponse
{
    Contact::create([
        'name' => $contactData->name,
        'email' => $contactData->email,
    ]);

    return redirect()->back();
}
```

### Eloquent Castable

[](#eloquent-castable)

DataTransferObjects can be used as a cast in eloquent models

```
class Contact extends Model
{
    protected $casts = [
        'address' => AddressData::class,
    ];
}
```

If the column is nullable, you have to append the cast parameter "nullable":

```
class Contact extends Model
{
    protected $casts = [
        'address' => AddressData::class . ':nullable',
    ];
}
```

Casting arrays of Data Transfer Objects:

```
use Ccharz\DtoLite\AsDataTransferObjectCollection;

/**
 * Get the attributes that should be cast.
 *
 * @return array
 */
protected function casts(): array
{
    return [
        'addresses' => AsDataTransferObjectCollection::of(AddressData::class),
    ];
}
```

### Response

[](#response)

Data Transfer Objects are automatically converted to an response if returned from a controller

```
class ContactController extends Controller {
    public function show(Contact $contact): ContactData
    {
        return ContactData::make($contact);
    }
}
```

You can also return a [resource collection](https://laravel.com/docs/11.x/eloquent-resources#resource-collections) of data transfer objects

```
class ContactController extends Controller {
    public function index()
    {
        return ContactData::resourceCollection(Contact::paginate());
    }
}
```

### Map to DTO Array

[](#map-to-dto-array)

An array can automatically be mapped to an array of the DTO:

```
$addresses = [
    [
        'country' => 'AT',
        'zip' => '8010',
    ],
    [
        'country' => 'AT',
        'zip' => '8010',
    ]
];

AddressData::mapToDtoArray($addresses);
```

Typescript Definitions
----------------------

[](#typescript-definitions)

You can use  to automatically generate typescript definitions for your Data Transfer Objects and Enums.

```
namespace App\Data;

use Spatie\TypeScriptTransformer\Attributes\TypeScript;

#[TypeScript]
readonly class AddressData extends DataTransferObject
{
    public function __construct(
        public readonly ?string $country = null,
        public readonly ?string $zip = null,
        public readonly ?string $location = null,
        public readonly ?string $street = null,
        public readonly ?string $streetnumber = null,
        public readonly ?string $stair = null,
        public readonly ?string $top = null,
    ) {
    }
}
```

generates to the following typescript definition:

```
declare namespace App.Data {
    export type AddressData = {
        country: string | null;
        zip: string | null;
        location: string | null;
        street: string | null;
        streetnumber: string | null;
        stair: string | null;
        top: string | null;
    };
}
```

Artisan Command
---------------

[](#artisan-command)

To create a new data transfer object, use the make:dto Artisan command:

```
php artisan make:dto Address
```

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance79

Regular maintenance activity

Popularity20

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

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

Recently: every ~105 days

Total

18

Last Release

109d ago

Major Versions

v1.3.0 → v2.0.02024-07-11

v2.0.0 → v3.0.02024-07-16

### Community

Maintainers

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

---

Top Contributors

[![ccharz](https://avatars.githubusercontent.com/u/2725238?v=4)](https://github.com/ccharz "ccharz (33 commits)")

---

Tags

laraveldto

###  Code Quality

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[grumpydictator/firefly-iii

Firefly III: a personal finances manager.

23.9k69.5k](/packages/grumpydictator-firefly-iii)[firefly-iii/data-importer

Firefly III Data Import Tool.

8035.8k](/packages/firefly-iii-data-importer)[markwalet/nova-modal-response

A Laravel Nova asset for Modal responses on an action.

17878.9k](/packages/markwalet-nova-modal-response)[ronasit/laravel-helpers

Provided helpers function and some helper class.

2085.6k31](/packages/ronasit-laravel-helpers)[team-nifty-gmbh/tall-datatables

Server-side rendered datatables for Laravel and Livewire

1320.9k4](/packages/team-nifty-gmbh-tall-datatables)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.4k](/packages/tomshaw-electricgrid)

PHPackages © 2026

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