PHPackages                             olexin-pro/data-transfer-object - 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. olexin-pro/data-transfer-object

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

olexin-pro/data-transfer-object
===============================

DTO with convert

v0.2.2(5mo ago)08MITPHPPHP ^8.3

Since Nov 24Pushed 5mo agoCompare

[ Source](https://github.com/olexin-pro/data-transfer-object)[ Packagist](https://packagist.org/packages/olexin-pro/data-transfer-object)[ RSS](/packages/olexin-pro-data-transfer-object/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (11)Used By (0)

📘 Data Transfer Object
======================

[](#-data-transfer-object)

[![Latest Version on Packagist](https://camo.githubusercontent.com/46b4200b6c35997c9feaf6b43e78429c0874f16ede2692f63fb3ea50f43f3b72/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f6c6578696e2d70726f2f646174612d7472616e736665722d6f626a6563742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/olexin-pro/data-transfer-object)[![PHP Version](https://camo.githubusercontent.com/dba1774a5fd95fcd9adc01a14809eb953b3a7e39aea9864927053f9d398d4f9e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e332d626c75653f7374796c653d666c61742d737175617265)](https://www.php.net/releases/)[![License](https://camo.githubusercontent.com/fb680a3031ac0765bd0353fec44f7daf0515cd6992cd8961a600adb821cda8c0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f6c6578696e2d70726f2f646174612d7472616e736665722d6f626a6563742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/olexin-pro/data-transfer-object)[![Tests](https://camo.githubusercontent.com/69fa4fa07629c89f04b490e7c193224406314b8eb2d813c1ae8f2771d5bb5af6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6f6c6578696e2d70726f2f646174612d7472616e736665722d6f626a6563742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/olexin-pro/data-transfer-object/actions)

A powerful, strict, and production-ready DTO layer for PHP/Laravel.

This package provides automatic type conversion, PHP 8 Attribute mapping, nested DTO support, Laravel Casts, and seamless integration with API Resources. It ensures your data is validated, normalized, and strongly typed from the moment it enters your application.

✨ Features
----------

[](#-features)

- 🚀 **Auto-Conversion:** Automatically transforms input arrays/JSON into strongly typed objects.
- 🔍 **PHP 8 Attributes:** Declarative field mapping with `#[Field]`.
- 🔄 **Enum Casting:** Strict type enforcement using native Enums.
- 🧩 **Nested DTOs:** Recursively resolves complex data structures.
- ⚙️ **Strict Validation:** Throws errors on type mismatches or missing required fields.
- 📦 **Laravel Integration:** Includes Model Casts and Form Request mapping.
- 🌐 **Resource Pipeline:** Request → DTO → API Resource flow.
- 🪞 **High Performance:** Uses reflection caching to minimize overhead.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Usage Guide](#-usage-guide)
    - [Manual Instantiation](#manual-instantiation)
    - [Nested DTOs](#nested-dtos)
- [Laravel Integration](#-laravel-integration)
    - [Request Injection](#request-injection)
    - [Model Casts](#model-casts)
    - [API Resources](#api-resources)
- [Reference](#-reference)
    - [Supported Types](#supported-types)
- [Testing](#-testing)
- [License](#-license)

---

📦 Installation
--------------

[](#-installation)

Requires **PHP 8.3+**

```
composer require olexin-pro/data-transfer-object
```

---

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Define your DTO

[](#1-define-your-dto)

Create a class extending `AbstractDTO` and use attributes to define fields.

```
namespace App\DTO;

use Ol3x1n\DataTransferObject\AbstractDTO;
use Ol3x1n\DataTransferObject\Field;
use Ol3x1n\DataTransferObject\Enums\TypeEnum;

class UserDTO extends AbstractDTO
{
    #[Field('id', TypeEnum::INT, required: true)]
    public int $id;

    #[Field('name', TypeEnum::STRING)]
    public ?string $name;

    #[Field('profile', TypeEnum::DTO)]
    public ?ProfileDTO $profile; // Nested DTO
}
```

### 2. Use it

[](#2-use-it)

```
$data = [
    'id' => '5',          // Will be cast to int(5)
    'name' => 'Alex',
    'profile' => [        // Will be hydrated into ProfileDTO
        'age' => '30',
        'country' => 'USA'
    ]
];

$dto = new UserDTO($data);

echo $dto->id; // 5 (int)
echo $dto->profile->country; // "USA"
```

---

🎯 Usage Guide
-------------

[](#-usage-guide)

### Manual Instantiation

[](#manual-instantiation)

You can instantiate a DTO with any iterable (array or collection). Keys are automatically normalized from `camelCase` to `snake_case` during processing.

```
$dto = new UserDTO([
    'id' => 100,
    'name' => 'John Doe'
]);
```

### Nested DTOs

[](#nested-dtos)

Complex structures are handled automatically. Simply typehint the property with another DTO class and use `TypeEnum::DTO`.

```
class ProfileDTO extends AbstractDTO
{
    #[Field('age', TypeEnum::INT)]
    public ?int $age;
}

class UserDTO extends AbstractDTO
{
    #[Field('profile', TypeEnum::DTO)]
    public ProfileDTO $profile;
}
```

**Input:**

```
{
    "profile": { "age": 25 }
}
```

**Result:** `$dto->profile` is an instance of `ProfileDTO`.

---

📥 Laravel Integration
---------------------

[](#-laravel-integration)

### Request Injection

[](#request-injection)

The package integrates seamlessly with Laravel's Service Container. You can typehint a DTO in your Controller method, and it will automatically hydrate from the current Request (supporting JSON, Form Data, Query Params).

```
use App\DTO\UserDTO;

class UserController extends Controller
{
    public function store(UserDTO $dto)
    {
        // $dto is already validated and hydrated from the request
        $user = $this->service->create($dto);

        return new UserResource($user);
    }
}
```

Alternatively, use `fromRequest`:

```
public function update(Request $request)
{
    $dto = UserDTO::fromRequest($request);
}
```

### Model Casts

[](#model-casts)

Store DTOs directly in your database using Laravel's Custom Casts. The DTO is serialized to JSON on save and hydrated back to a DTO on retrieval.

**In your Model:**

```
use Ol3x1n\DataTransferObject\Laravel\DTOCast;
use App\DTO\ProfileDTO;

class User extends Model
{
    protected $casts = [
        'profile' => ProfileDTO::class,
    ];
}
```

**Usage:**

```
$user->profile->age = 31;
$user->save(); // Saved as JSON column
```

### API Resources

[](#api-resources)

DTOs implement `Arrayable`, making them compatible with Laravel API Resources.

```
class UserResource extends JsonResource
{
    public function toArray($request)
    {
        // Works whether $this->resource is a Model or a DTO
        return [
            'id' => $this->id,
            'name' => $this->name,
        ];
    }
}

// Returning a DTO directly
return new UserResource($userDTO);
```

---

🧰 Reference
-----------

[](#-reference)

### Supported Types (`TypeEnum`)

[](#supported-types-typeenum)

The `#[Field]` attribute requires a type definition from `TypeEnum`.

Enum CaseDescription`TypeEnum::INT`Casts to integer`TypeEnum::FLOAT`Casts to float`TypeEnum::STRING`Casts to string`TypeEnum::BOOLEAN`Casts to boolean`TypeEnum::ARRAY`Casts to array`TypeEnum::DATE`Handles date strings`TypeEnum::DTO`Hydrates a nested DTO`TypeEnum::COLLECTION`Hydrates a collection of DTOs/items`TypeEnum::DYNAMIC`No casting, keeps original type---

🧠 Architecture &amp; Principles
-------------------------------

[](#-architecture--principles)

1. **Immutability:** DTOs are designed to be immutable after instantiation.
2. **Safety:** Internal fields (`_raw`, etc.) are hidden.
3. **Normalization:** Input keys are normalized (snake\_case/camelCase handling).
4. **Performance:** Reflection metadata is cached to ensure production speed.

---

🧪 Testing
---------

[](#-testing)

Run the full test suite:

```
vendor/bin/phpunit
```

---

📝 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE.md).

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance71

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

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

Total

10

Last Release

163d ago

PHP version history (2 changes)v0.0.1PHP ^8.3

v0.0.2PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/140a9b26ee37fdccbed9cf124340643fbeb2d4e11ab1a5382dda8c8f34a69afe?d=identicon)[ol3x1n](/maintainers/ol3x1n)

---

Top Contributors

[![olexin-pro](https://avatars.githubusercontent.com/u/9531609?v=4)](https://github.com/olexin-pro "olexin-pro (1 commits)")

---

Tags

laravellaravel-packagesdata-transfer-objectdto

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/olexin-pro-data-transfer-object/health.svg)

```
[![Health](https://phpackages.com/badges/olexin-pro-data-transfer-object/health.svg)](https://phpackages.com/packages/olexin-pro-data-transfer-object)
```

###  Alternatives

[barryvdh/laravel-ide-helper

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

14.9k123.0M686](/packages/barryvdh-laravel-ide-helper)[spatie/laravel-enum

Laravel Enum support

3655.4M31](/packages/spatie-laravel-enum)[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[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

255.2k](/packages/aedart-athenaeum)[laracraft-tech/laravel-useful-additions

A collection of useful Laravel additions!

58109.4k](/packages/laracraft-tech-laravel-useful-additions)

PHPackages © 2026

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