Each property of a data object should be transformed into a usable type to communicate via JSON.
No complex transformations are required for the default types (string, bool, int, float, enum and array), but special types like Carbon or a Laravel Model will need extra attention.
Transformers are simple classes that will convert a complex type to something simple like a string or int. For example, we can transform a Carbon object to 16-05-1994, 16-05-1994T00:00:00+00 or something completely different.
There are two ways you can define transformers: locally and globally.
Global transformers are defined in the data.php config file and are used when no local transformer for a property was added. By default, there are two transformers:
useIlluminate\Contracts\Support\Arrayable;useSpatie\LaravelData\Transformers\ArrayableTransformer;useSpatie\LaravelData\Transformers\DateTimeInterfaceTransformer;/* * Global transformers will take complex types and transform them into simple * types. */'transformers'=> [DateTimeInterface::class=>DateTimeInterfaceTransformer::class,Arrayable::class=>ArrayableTransformer::class,],
The package will look through these global transformers and tries to find a suitable transformer. You can define transformers for:
It is possible to get an array representation of a data object without transforming the properties. This means Carbon objects won't be transformed into strings. And also, nested data objects and DataCollections won't be transformed into arrays. You can do this by calling the all method on a data object like this: