Download the PHP package fab2s/laravel-dt0 without Composer
On this page you can find all versions of the php package fab2s/laravel-dt0. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download fab2s/laravel-dt0
More information about fab2s/laravel-dt0
Files in fab2s/laravel-dt0
Package laravel-dt0
Short Description Immutable Data Transfer Objects (DTO) for Laravel with validation, Eloquent casting, and encryption
License MIT
Homepage https://github.com/fab2s/laravel-dt0
Informations about the package laravel-dt0
Laravel Dt0
A powerful Laravel integration for fab2s/dt0, bringing true immutability, Laravel validation, and Eloquent model casting to your Data Transfer Objects.
Why Dt0?
Traditional DTOs with mutable properties miss the core purpose: guaranteeing that data won't be accidentally modified. Dt0 leverages PHP 8.2+'s native readonly properties to enforce immutability at the language level, not by convention, but by design.
Key Benefits:
- True Immutability — Readonly properties prevent accidental modifications (fatal error, not silent bug)
- Laravel Validation — Full power of Laravel's validation rules on DTO properties
- Eloquent Casting — Use DTOs directly as model attributes with automatic serialization
- Flexible Hydration — Create from arrays, JSON strings, or other instances
- Type Safety — Strong typing with bidirectional casting support,
strict_typesenforced, PHPStan level 9 clean - Performance — Logic compiled once per process and cached
Note: This package extends fab2s/dt0 with Laravel-specific features (validation, Eloquent casting). All features from the base package, including property casting, property renaming, default values, output filtering, and more, work seamlessly here. Visit the dt0 documentation for the complete feature set.
Flexible, not dogmatic. While immutability is the core feature, Dt0 doesn't force it. Use mutable properties when needed. Expose protected properties via with(). The package provides capabilities; you decide how to use them.
Dt0 vs spatie/laravel-data
Feature Comparison
| Feature | Dt0 | spatie/laravel-data |
|---|---|---|
| True immutability (readonly) | Native, enforced | Optional, by convention |
| Laravel validation | Built-in | Built-in |
| Eloquent model casting | Built-in | Via package |
| Encrypted properties | Built-in (EncryptedCaster) |
Manual |
| Bidirectional casting | #[Cast(in:, out:, both:)] |
Separate Cast + Transformer |
| Property renaming | #[Cast(renameFrom:, renameTo:)] |
#[MapInputName] / #[MapOutputName] |
| Dependencies | 2 illuminate components | Full framework service provider |
| PHPStan level | 9 | 6 |
| PHP 8.2+ readonly | First-class | Supported but not enforced |
Performance
Benchmarks from fab2s/dt0 (reproducible via the benchmark script):
| Operation | Dt0 | spatie/laravel-data | Speedup |
|---|---|---|---|
| Simple DTO (8 props, 5 casts) | 142 µs | 1,158 µs | ~8x faster |
| Complex DTO (nested + arrays) | 742 µs | 3,628 µs | ~5x faster |
| toArray() (simple, cached) | 3.6 µs | 679 µs | ~189x faster |
| toArray() (nested, cached) | 3.6 µs | 2,056 µs | ~571x faster |
Table of Contents
- Installation
- Quick Start
- Real-World Example
- Core Features
- Creating DTOs
- Factory Methods
- Serialization
- Immutable Updates
- Laravel Validation
- Defining Rules
- Rule Priority
- Triggering Validation
- Custom Validation Rules
- Model Attribute Casting
- Casters
- Built-in Casters
- CollectionOfCaster
- EncryptedCaster
- Artisan Generator
- Compatibility
- Contributing
- License
Installation
Quick Start
Real-World Example
A complete request-to-response flow with validation, Eloquent casting, and typed access:
Form Request Integration
Dt0 pairs with Form Requests for teams that prefer that pattern:
Core Features
Creating DTOs
Extend fab2s\Dt0\Laravel\Dt0 for full Laravel integration:
Factory Methods
Dt0 provides multiple ways to instantiate:
new vs Factory Methods
When using `new` directly with **promoted readonly properties that have a default value**, PHP initializes them immediately, **before** Dt0 can apply casting. Promoted properties without defaults behave normally.
See [Dt0 readme](https://github.com/fab2s/dt0/?tab=readme-ov-file#new-vs-factory-methods) for more details.
**Best practice**: Use factory methods (`make`, `from`, `fromArray`, etc.) for full casting support. Reserve `new` for cases where you're passing already-correct types or relying on defaults.
Serialization
Immutable Updates
Create modified copies without mutating the original:
Laravel Validation
Laravel Dt0 integrates seamlessly with Laravel's validation system. Validation runs on input data before any casting or instantiation.
Note: This package uses Laravel's
Validatorunder the hood. All Laravel validation rules, custom rule objects, and error message customization work exactly as documented in Laravel.
Defining Rules
Rules can be defined at three levels:
1. Via Validate Class Attribute
2. Via Rules Class Attribute
3. Via Rule Property Attribute
When to use each approach:
| Approach | Best for |
|---|---|
Property #[Rule] |
Keeping rules close to properties, self-documenting DTOs |
Class #[Rules] |
Grouping rules together, inherited properties |
#[Validate] Rules |
Default/fallback rules that subclasses can override |
Rule Priority
When the same property has rules defined at multiple levels, only the highest priority rule applies — rules are not merged.
Priority order: Property #[Rule] > Class #[Rules] > #[Validate] Rules
Triggering Validation
Custom Validation Rules
Use Laravel's custom rule classes:
Model Attribute Casting
Use DTOs directly as Eloquent model attributes with automatic JSON serialization:
Usage
Requirements
Your DTO must either:
- Extend
fab2s\Dt0\Laravel\Dt0, or - Extend
fab2s\Dt0\Dt0and usefab2s\Dt0\Laravel\LaravelDt0Trait
Casters
Casters transform property values during hydration (input) and serialization (output). The #[Cast] attribute supports in:, out:, and both: parameters:
Built-in Casters
From fab2s/dt0:
| Caster | Description |
|---|---|
ScalarCaster |
Converts to int, float, bool, or string |
ArrayOfCaster |
Casts each array element to a type (scalar, Dt0, or enum) |
DateTimeCaster |
Parses to DateTime/DateTimeImmutable |
CarbonCaster |
Parses to Carbon/CarbonImmutable (requires nesbot/carbon) |
DateTimeFormatCaster |
Formats DateTime to string |
MathCaster |
High-precision decimals (requires fab2s/math) |
Dt0Caster |
Explicit casting to a Dt0 class |
ClassCaster |
Instantiates arbitrary classes |
CollectionOfCaster
Laravel Dt0 adds CollectionOfCaster for strongly-typed Laravel Collections:
Supported types:
- Dt0 classes — Each element cast via
Dt0::from() - Enums — Each element cast to the enum
- Scalars —
int,float,bool,string
EncryptedCaster
Encrypt/decrypt property values using Laravel's encryption:
Auto-detection: On input, the caster automatically detects Laravel's encrypted payload format. Encrypted values are decrypted, while plaintext strings, arrays, and objects pass through unchanged. This allows flexible initialization from both plaintext and encrypted sources.
Custom encryption key and cipher: By default, EncryptedCaster uses your APP_KEY and app cipher. When you need different values, always use the config: prefix to reference config paths rather than hardcoding key material or cipher names in your source code. This also avoids source code changes when rotating keys or updating ciphers — just update the config:
The config values support base64:-encoded keys, just like APP_KEY:
Other options:
Performance: Encrypter instances are statically cached by key and cipher combination. Multiple DTO instances or properties using the same encryption key share a single Encrypter, avoiding repeated instantiation overhead.
Stack trace safety: All sensitive parameters (keys, plaintext values) are annotated with #[\SensitiveParameter] and redacted from exception stack traces.
Eloquent model safety: When using an EncryptedCaster DTO as an Eloquent model attribute, calling $model->toArray() or $model->toJson() will trigger the DTO's output casters, meaning encrypted fields are always encrypted in the serialized output. Plaintext is only accessible through direct property access on the DTO instance ($model->myDto->apiKey).
Artisan Generator
Scaffold new DTOs with the make:dt0 Artisan command:
The service provider is auto-discovered — no manual registration needed.
Compatibility
| PHP | Laravel | Status |
|---|---|---|
| 8.2 | 11.x, 12.x | Supported |
| 8.3 | 11.x, 12.x, 13.x | Supported |
| 8.4 | 11.x, 12.x, 13.x | Supported |
| 8.5 | 13.x | Supported |
Contributing
Contributions are welcome! Please feel free to:
- Open issues for bugs or feature requests
- Submit pull requests
- Improve documentation
License
Laravel Dt0 is open-sourced software licensed under the MIT license.
All versions of laravel-dt0 with dependencies
fab2s/dt0 Version ^2.0.0
illuminate/translation Version ^11.0|^12.0|^13.0
illuminate/validation Version ^11.0|^12.0|^13.0