Micro Dream Form ValidateMicro Dream Form Validate
Home
Plugin
IDE Support
Source Code
  • 6.x
  • 5.x
  • 简体中文
  • English
Home
Plugin
IDE Support
Source Code
  • 6.x
  • 5.x
  • 简体中文
  • English
  • Introduction
  • Guide

    • Start
    • Validator
    • Validate Scene
    • Validation Events
    • Types Casting
    • Built in rules
    • Custom Rules
    • Custom Error Messages
    • Data Processor
    • Validator Collection
  • Update log

Types Casting

Types casting allows you to transform data to a specific type after it has passed validation. This is particularly useful for ensuring data type consistency, for example, converting string numbers from a request into integers or floats.

How to Use

Define a protected $casts property in your Validate class. This property is an array where the keys are the field names to be cast, and the values are the target types.

class UserId
{
    public function __construct(protected readonly int $id) {}
}

class TestValidate extends Validate
{
    protected array $rule = [
        'name' => 'required|string',
        'age'  => 'required|integer',
        'id'   => 'required|int|min:0',
    ];

    protected array $casts = [
        'age' => 'int',
        'id'  => UserId::class
    ];
}

When the check method is called, the age field will be cast to an integer, and the id field will be cast to a UserId object.

$v = new TestValidate();
$data = $v->check([
    'name' => 'John Doe',
    'age'  => '30',
    'id'   => 123
]);

// The value of $data['age'] will be (int) 30
// The value of $data['id'] will be an instance of UserIdCaster

Built-in Types

int

Casts the value to an integer.

protected $casts = ['age' => 'int'];
// '30' -> 30

float

Casts the value to a float.

protected $casts = ['price' => 'float'];
// '19.99' -> 19.99

decimal

Casts the value to a float with a specified number of decimal places.

protected $casts = [
    'price' => 'decimal:2', // Keep two decimal places
    'rate'  => 'decimal:4'  // Keep four decimal places
];
// '19.99' -> 19.99
// '0.12345' -> 0.1235

string

Casts the value to a string.

protected $casts = ['zipcode' => 'string'];
// 12345 -> '12345'

bool

Casts the value to a boolean. '0', 0, and false will be converted to false. Other values (including the string 'false') will be converted to true.

protected $casts = ['is_active' => 'bool'];
// '1' -> true
// 0 -> false

array

Casts a JSON string to a PHP array.

protected $casts = ['options' => 'array'];
// '{"color":"red"}' -> ['color' => 'red']

object

Casts a JSON string to a PHP stdClass object.

protected $casts = ['options' => 'object'];
// '{"color":"red"}' -> (object) ['color' => 'red']

json

Casts a PHP array or object to a JSON string.

protected $casts = ['properties' => 'json'];
// ['color' => 'red'] -> '{"color":"red"}'

json_unicode

Casts a PHP array or object to a Unicode-escaped JSON string.

protected $casts = ['properties' => 'json_unicode'];
// ['name' => '墨娘'] -> '{"name":"\u58a8\u5a18"}'

collection

Casts an array or JSON string to an Itwmw\Validation\Support\Collection\Collection object.

protected $casts = ['users' => 'collection'];

Enum class

Casts a value to a specified PHP enumeration.

Backed Enum Example

// enum ProductType: int { case BOOK = 1; ... }
protected $casts = ['product_type' => ProductType::class];

// 1 -> ProductType::BOOK
// 'BOOK' -> ProductType::BOOK

Pure Enum Example

// enum LoginFrom { case PC; ... }
protected $casts = ['login_from' => LoginFrom::class];

// 'PC' -> LoginFrom::PC

Custom Classes

You can cast a value to your own custom class object.

Simple Class

If your class constructor accepts a single argument, you can use the class name directly as the cast type.

// class UserId { public function __construct(protected readonly int $id) {} }
protected $casts = ['user_id' => UserId::class];
// 123 -> new UserId(123)

Castable Class

For more complex casting logic, you can implement the Itwmw\Validate\Support\Concerns\ValidateCastable interface.

use Itwmw\Validate\Support\Concerns\ValidateCastable;

class UserIdCaster extends UserId implements ValidateCastable
{
    public static function castsAttributes(string $field, mixed $value, array $attributes): static
    {
        // Custom casting logic
        return new static($value);
    }
}

// --- In Validate Class ---
protected $casts = ['user_id' => UserIdCaster::class];

Array

You can use casters on array fields, including using the * wildcard.

class TestValidate extends Validate
{
    protected $rule = [
        'users'        => 'array:@list',
        'users.*'      => 'array:name,id',
        'users.*.name' => 'required|string',
        'users.*.id'   => 'required|int|min:0',
    ];

    protected $casts = [
        'users.*.id' => 'integer',
    ];
}

$data = $v->check([
    'users' => [
        ['name' => 'Alice', 'id' => '1'],
        ['name' => 'Bob', 'id' => '2'],
    ]
]);

// $data['users'][0]['id'] will be (int) 1
// $data['users'][1]['id'] will be (int) 2

Multiple Casts

You can apply multiple casters to a single field. They will be executed in order.

protected $casts = [
    'options' => ['array', 'json_unicode']
];

// '[{"name":"虞灪"}]' -> (step 1: array) [['name' => '虞灪']] -> (step 2: json_unicode) '[{"name":"\u865e\u706a"}]'
Prev
Validation Events
Next
Built in rules