โœ…
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
  • Castable classes
  • Callable casts

Was this helpful?

  1. Type Casting

Create Your Own Type Cast

Castable classes

You can easily create new Castable types for your project by implementing the WendellAdriel\ValidatedDTO\Casting\Castable interface. This interface has a single method that must be implemented:

public function cast(string $property, mixed $value): mixed;

Let's say that you have a URLWrapper class in your project, and you want that when passing a URL into your DTO it will always return a URLWrapper instance instead of a simple string:

class URLCast implements Castable
{
    public function cast(string $property, mixed $value): URLWrapper
    {
        return new URLWrapper($value);
    }
}

Then you could apply this to your DTO:

class CustomDTO extends ValidatedDTO
{
    protected function rules(): array
    {
        return [
            'url' => ['required', 'url'],
        ];
    }

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

    protected function casts(): array
    {
        return [
            'url' => new URLCast(),
        ];
    }
}

Callable casts

You can also create new Castable types for your project by using a callable/callback:

class CustomDTO extends ValidatedDTO
{
    protected function rules(): array
    {
        return [
            'url' => ['required', 'url'],
        ];
    }

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

    protected function casts(): array
    {
        return [
            'url' => function (string $property, mixed $value) {
                return new URLWrapper($value);
            },
        ];
    }
}
PreviousAvailable TypesNextCasting Eloquent Model properties to DTOs

Last updated 1 year ago

Was this helpful?

๐Ÿงช