Casting Attributes
Reference for type casting attributes and 20+ built-in cast classes.
The Cast Attribute
Section titled “The Cast Attribute”#[Cast(string $castClass)]
Section titled “#[Cast(string $castClass)]”Cast property to a specific type:
use Event4u\DataHelpers\SimpleDTO\Attributes\Cast;use Event4u\DataHelpers\SimpleDTO\Casts\DateTimeCast;
#[Cast(DateTimeCast::class)]public readonly Carbon $createdAt;Built-in Cast Classes
Section titled “Built-in Cast Classes”Primitive Types
Section titled “Primitive Types”#[Cast(StringCast::class)] // Cast to string#[Cast(IntCast::class)] // Cast to integer#[Cast(FloatCast::class)] // Cast to float#[Cast(BoolCast::class)] // Cast to boolean#[Cast(ArrayCast::class)] // Cast to arrayDate & Time
Section titled “Date & Time”#[Cast(DateTimeCast::class)] // Cast to Carbon#[Cast(DateCast::class)] // Cast to Carbon (date only)#[Cast(TimestampCast::class)] // Cast from timestamp#[Cast(EnumCast::class)] // Cast to enum#[Cast(BackedEnumCast::class)] // Cast to backed enumCollections
Section titled “Collections”#[Cast(CollectionCast::class)] // Cast to Collection#[Cast(DataCollectionCast::class)] // Cast to DataCollectionObjects & JSON
Section titled “Objects & JSON”#[Cast(ObjectCast::class)] // Cast to object#[Cast(JsonCast::class)] // Cast JSON to arraySecurity
Section titled “Security”#[Cast(EncryptedCast::class)] // Encrypt/decrypt#[Cast(HashCast::class)] // One-way hash#[Cast(DecimalCast::class)] // Cast to decimal#[Cast(UuidCast::class)] // Cast to UUID#[Cast(IpAddressCast::class)] // Cast to IP address#[Cast(UrlCast::class)] // Cast to URLCast Options
Section titled “Cast Options”// Date format#[Cast(DateTimeCast::class, format: 'Y-m-d H:i:s')]public readonly Carbon $createdAt;
// Nullable cast#[Cast(IntCast::class, nullable: true)]public readonly ?int $age;
// Default value#[Cast(StringCast::class, default: 'N/A')]public readonly string $name;Custom Casts
Section titled “Custom Casts”use Event4u\DataHelpers\SimpleDTO\Contracts\Cast;
class UpperCaseCast implements Cast{ public function cast(mixed $value): string { return strtoupper((string) $value); }}
#[Cast(UpperCaseCast::class)]public readonly string $name;Real-World Example
Section titled “Real-World Example”class UserDTO extends SimpleDTO{ public function __construct( #[Cast(StringCast::class)] public readonly string $name,
#[Cast(DateTimeCast::class)] public readonly Carbon $birthDate,
#[Cast(EnumCast::class)] public readonly Status $status,
#[Cast(EncryptedCast::class)] public readonly string $ssn, ) {}}See Also
Section titled “See Also”- Type Casting - Detailed guide
- Validation Attributes - Validation reference