โœ…
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

Introduction

You can easily cast your DTO properties by defining a casts method in your DTO:

protected function casts(): array
{
    return [
        'name' => new StringCast(),
        'age'  => new IntegerCast(),
        'created_at' => new CarbonImmutableCast(),
    ];
}

Alternatively, for simpler cases, you can use the Cast attribute:

use WendellAdriel\ValidatedDTO\Attributes\Cast;
use WendellAdriel\ValidatedDTO\Concerns\EmptyCasts;

class UserDTO extends ValidatedDTO
{
    use EmptyCasts;

    public string $name;

    public string $email;

    #[Cast(BooleanCast::class)]
    public bool $active;

    #[Cast(IntegerCast::class)]
    public ?int $age;

    #[Cast(type: ArrayCast::class, param: FloatCast::class)]
    public ?array $grades;
}

If you're using attributes to define the casting of your properties or if you don't have any casting for the properties, you can use the EmptyCasts trait to avoid having to define the casts() method.

PreviousCustom ExceptionsNextAvailable Types

Last updated 1 year ago

Was this helpful?

๐Ÿงช