Format property here is an Enum and looks like this:
DateTime and Enum, respectively.
These types cannot be automatically created. A cast is needed to construct them from a string.
There are two types of casts: local and global casts.
Local Casts
Local casts are defined within the data object itself and can be added using attributes:Cast Parameters
It is possible to provide parameters to the casts like this:Global Casts
Global casts are not defined on the data object but in yourdata.php config file:
- a specific implementation (e.g. CarbonImmutable)
- an interface (e.g. DateTimeInterface)
- a base class (e.g. Enum)
DateTimeInterface cast, this means we can update our data object like this:
Creating Your Own Casts
It is possible to create your casts. You can read more about this in the advanced chapter.Casting Arrays or Collections of Non-Data Types
We’ve already seen how collections of data can be made of data objects, the same is true for all other types if correctly typed. Let say we have an array of DateTime objects:cast_and_transform_iterables feature in the data config file (this feature will be enabled by default in laravel-data v5):
ReleaseData object with an array of strings which will be cast into an array DateTime objects:
For this feature to work, a cast should not only implement the
Cast interface but also the IterableItemCast. The signatures of the cast and castIterableItem methods are exactly the same, but they’re called on different times. When casting a property like a DateTime from a string, the cast method will be used, when transforming an iterable property like an array or Laravel Collection where the iterable item is typed using an annotation, then each item of the provided iterable will trigger a call to the castIterableItem method.