Skip to main content
Casts take simple values and transform them into complex types. For example, 16-05-1994T00:00:00+00 could be cast into a Carbon object.

Cast Interface

Implement the Cast interface:

Parameters

  • property - DataProperty object representing the property being cast (read more)
  • value - The value to be cast
  • properties - Array of current properties for creating the data object
  • creationContext - Context containing:
    • dataClass - The data class being created
    • validationStrategy - The validation strategy in use
    • mapPropertyNames - Whether property names should be mapped
    • disableMagicalCreation - Whether to use magical creation methods
    • ignoredMagicalMethods - Which magical methods are ignored
    • casts - Collection of global casts

Return Value

Return the casted value, or an Uncastable object if the cast cannot be performed.

Handling Null

Casts never receive null values. The package keeps null as null to avoid creating values out of thin air. Use magic methods if you need to replace null values.

Castables

Allow value objects to define their own casting logic:

Castable with Arguments

Pass arguments to the castable:

Castable Implementation

Implement the Castable interface:

Casting Iterable Values

Cast items in arrays or Collections by implementing IterableItemCast:
The castIterableItem method is called for each item. Check $property->type->iterableItemType to get the target type.

Combining Casts and Transformers

Create a class that both casts and transforms:
Use with the WithCastAndTransformer attribute: