
Generate modern, type-safe Data Transfer Objects (DTOs) in Laravel from clean YAML definitions β with automatic validation, nested support, and fluent collection handling.
Laravel Arc is a powerful Laravel package that simplifies Data Transfer Object (DTO) management through YAML-driven generation. Define your DTOs in simple YAML files and let Laravel Arc generate type-safe, validated PHP classes with automatic property access and comprehensive collection support.
Think of it as Laravel API Resources, but with stronger typing, automatic validation, and generated from YAML definitions.
graph TD
A[YAML Definition] --> B[DTO Generator]
B --> C[Generated DTO Class]
A --> D[Field Types]
A --> E[Transformers]
A --> F[Validation Rules]
A --> G[Behavioral Traits]
C --> H[Functional Traits]
H --> I[ValidatesData]
H --> J[ConvertsData]
H --> K[DtoUtilities]
G --> L[HasTimestamps]
G --> M[HasUuid]
G --> N[HasSoftDeletes]
G --> O[HasVersioning]
G --> P[HasTagging]
G --> Q[HasAuditing]
G --> R[HasCaching]
E --> S[String Transformers]
E --> T[Numeric Transformers]
E --> U[Custom Transformers]
C --> V[Model Integration]
C --> W[Collection Support]
C --> X[Export Formats]
style A fill:#e1f5fe
style C fill:#c8e6c9
style H fill:#fff3e0
style G fill:#f3e5f5
style E fill:#fce4ec
- π YAML-driven generation - Define DTOs in simple, readable YAML files
- π Automatic validation - Built-in Laravel validation rules support
- ποΈ Rich field types - 14+ field types including enums, UUIDs, nested DTOs, and JSON
- π Eloquent relationships - Full support for Laravel relationship types
- β‘ Direct property access - Clean, modern syntax with PHP 8.3+ features
- π¦ Collection management - Convert models to DTO collections like Laravel Resources
- π― Powerful trait system - Built-in behavioral traits for common functionality (HasTimestamps, HasUuid, HasSoftDeletes, HasVersioning, HasTagging, HasAuditing, HasCaching) plus 3 functional traits (ValidatesData, ConvertsData, DtoUtilities) in every DTO
- π Field transformers - Automatically transform field values during DTO creation with 10 built-in transformers (trim, lowercase, uppercase, title_case, slugify, abs, encrypt, normalize_phone, clamp_max, clamp_min)
- π€ Multiple export formats - Export DTOs in 9 formats (JSON, YAML, CSV, XML, TOML, Markdown, PHP Array, Query String, MessagePack) with dedicated collection methods
- π οΈ Powerful CLI commands - Generate, list, and manage DTOs from the command line
- π Smart path resolution - Automatic namespace-to-path conversion with custom organization
- π¨ Enhanced error handling - Detailed error messages with actionable suggestions
- π¦ Zero configuration - Works out of the box with sensible defaults
- π§ͺ Fully tested - Comprehensive test suite with high coverage
composer require grazulex/laravel-arc
1. Create a DTO definition
php artisan dto:definition-init UserDTO --model=App\\Models\\User --table=users
2. Define your DTO in YAML
# dto-definitions/UserDTO.yaml
header:
dto: UserDTO
namespace: App\DTO
model: App\Models\User
traits:
- HasTimestamps
- HasUuid
fields:
name:
type: string
validation: [required, string, max:255]
transformers: [trim, title_case]
email:
type: string
validation: [required, email]
transformers: [trim, lowercase]
status:
type: string
default: "active"
validation: [required, in:active,inactive]
3. Generate your DTO
php artisan dto:generate UserDTO.yaml
4. Use your DTO
// Convert a model to DTO
$user = User::find(1);
$userDto = UserDTO::fromModel($user);
// Convert a collection to DTO collection (like Laravel Resources)
$users = User::all();
$userDtos = UserDTO::collection($users); // Returns DtoCollection
// OR
$userDtos = UserDTO::fromModels($users); // Alternative syntax
// API Resource format
return response()->json($userDtos->toArrayResource());
// Output: {"data": [{"id": 1, "name": "John", "email": "[email protected]", "status": "active"}]}
// Export in multiple formats - 9 formats available
$json = $userDto->toJson();
$yaml = $userDto->toYaml();
$csv = $userDto->toCsv();
$xml = $userDto->toXml();
$toml = $userDto->toToml();
$markdown = $userDto->toMarkdownTable();
$phpArray = $userDto->toPhpArray();
$queryString = $userDto->toQueryString();
$messagepack = $userDto->toMessagePack();
$collection = $userDto->toCollection();
// Collection exports (with data wrapper like Laravel Resources)
$jsonData = UserDTO::collectionToJson($users);
$csvData = UserDTO::collectionToCsv($users);
$xmlData = UserDTO::collectionToXml($users);
$yamlData = UserDTO::collectionToYaml($users);
$markdownData = UserDTO::collectionToMarkdownTable($users);
// Validation
$userDto = UserDTO::fromArray($request->all());
if (!$userDto->isValid()) {
return response()->json(['errors' => $userDto->getErrors()], 422);
}
π‘ Laravel Arc provides a powerful trait system with two types of traits:
Every DTO automatically includes these three powerful traits:
- ValidatesData - Provides validation methods (
validate()
,passes()
,fails()
) - ConvertsData - Provides conversion methods (
toJson()
,toCsv()
,toXml()
, etc.) - DtoUtilities - Provides utility methods (
getProperties()
,with()
,equals()
)
Add specific functionality by including traits in your YAML definition:
header:
traits:
- HasTimestamps # Adds created_at, updated_at fields and methods
- HasUuid # Adds id field with UUID validation
- HasSoftDeletes # Adds deleted_at field for soft deletes
- HasVersioning # Adds version field and versioning methods
- HasTagging # Adds tags field and tagging methods
- HasAuditing # Adds audit trail fields and methods
- HasCaching # Adds caching capabilities
Example usage:
// Using functional traits (automatic)
$userDto = UserDTO::fromArray($data);
if (UserDTO::passes($data)) {
$validated = UserDTO::validate($data);
}
// Using behavioral traits (if included)
$userDto = $userDto->addTag('premium')
->nextVersion()
->touch()
->cache(3600);
Automatically transform field values during DTO creation:
fields:
name:
type: string
transformers: [trim, title_case] # " john doe " β "John Doe"
email:
type: string
transformers: [trim, lowercase] # " [email protected] " β "[email protected]"
price:
type: decimal
transformers: [abs, clamp_min:0] # -19.99 β 19.99
Available transformers:
- String transformers:
trim
,lowercase
,uppercase
,title_case
,slugify
- Numeric transformers:
abs
,clamp_max
,clamp_min
- Security transformers:
encrypt
- Phone transformers:
normalize_phone
(adds +33 prefix for French numbers starting with 0)
Complete documentation and guides:
- π Documentation Index - Complete navigation guide
- π Getting Started - Installation and first DTO
- π DTO Usage Guide - How to use DTOs in your Laravel application
- π― Examples Collection - Working examples and templates
- YAML Schema - Full YAML configuration reference
- Field Types - All available field types and options
- Traits Guide - Functional and behavioral traits system
- Validation Rules - Custom validation and error handling
- Collection Management - Working with DTO collections and API resources
- Export Formats - Export DTOs in 10 different formats
- Field Transformers - Automatic field value transformation
- Relationships - Eloquent relationships in DTOs
- Nested DTOs - Building complex nested structures
- CLI Commands - All available Artisan commands
- Advanced Usage - Advanced patterns and customizations
Laravel Arc is perfect for:
- API Development - Type-safe request/response handling
- Data Validation - Consistent validation across your application
- Model Transformation - Clean data layer separation
- Complex Forms - Nested form validation and processing
- API Resources - Alternative to Laravel Resources with stronger typing
Laravel Arc works out of the box, but you can customize it:
// config/dto.php
return [
'definitions_path' => base_path('database/dto_definitions'),
'output_path' => base_path('app/DTO'),
];
Check out the examples directory for complete working examples:
- Basic User DTO - Simple user DTO with validation
- API Controllers - Using DTOs in API controllers
- Export Formats - Export DTOs in 9 different formats
- Collection Methods - Advanced collection management
- Nested Structures - Complex nested DTOs
- Enum Support - Working with PHP enums
We welcome contributions! Please see our Contributing Guide for details.
Laravel Arc is open-sourced software licensed under the MIT license.