โœ…
Laravel Validated DTO
View on GitHub
  • โœ…Validated DTO for Laravel
  • ๐Ÿš€Getting Started
    • Installation
    • Configuration
    • Upgrade Guide
    • Changelog
  • ๐Ÿ˜ŽThe Basics
    • Generating DTOs
    • Defining DTO Properties
    • Defining Validation Rules
    • Creating DTO Instances
    • Accessing DTO Data
    • Defining Default Values
    • Transforming DTO Data
    • Mapping DTO properties
    • Simple DTOs
    • Resource DTOs
    • Wireable DTOs
    • Lazy Validation
    • Generating TypeScript Definitions
  • ๐ŸŽจCustomize
    • Custom Error Messages and Attributes
    • Custom Exceptions
  • ๐ŸงชType Casting
    • Introduction
    • Available Types
    • Create Your Own Type Cast
    • Casting Eloquent Model properties to DTOs
Powered by GitBook
On this page

Was this helpful?

  1. Type Casting

Casting Eloquent Model properties to DTOs

You can easily cast any Eloquent Model properties to your DTOs:

class MyModel extends Model
{
    protected $fillable = ['name', 'metadata'];

    protected $casts = [
        'metadata' => AttributesDTO::class,
    ];
}

The DTO class:

class AttributesDTO extends ValidatedDTO
{
    public int $age;

    public string $doc;

    protected function rules(): array
    {
        return [
            'age' => ['required', 'integer'],
            'doc' => ['required', 'string'],
        ];
    }

    protected function defaults(): array
    {
        return [];
    }

    protected function casts(): array
    {
        return [
            'age' => new IntegerCast(),
            'doc' => new StringCast(),
        ];
    }
}
PreviousCreate Your Own Type Cast

Last updated 2 years ago

Was this helpful?

๐Ÿงช