Skip to main content
Transformers allow you to transform complex types to simple types when converting a data object to an array or JSON. No complex transformations are required for default types (string, bool, int, float, enum and array), but special types like Carbon or Laravel Models need extra attention.

Local Transformers

When you want to transform a specific property, use an attribute with the transformer:
The DateTimeInterfaceTransformer is shipped with the package and transforms Carbon, CarbonImmutable, DateTime and DateTimeImmutable to a string.

Custom Format

Define a custom format:

Built-in Transformers

The package ships with several transformers:
Transforms date/time objects to strings:
Configure the format in config/data.php or pass it directly:

Global Transformers

Global transformers are defined in config/data.php and used when no local transformer is specified:
You can define transformers for:
  • A specific implementation (e.g. CarbonImmutable)
  • An interface (e.g. DateTimeInterface)
  • A base class (e.g. Enum)

Creating Custom Transformers

Create a custom transformer by implementing the Transformer interface:

Without Transforming

Get an array representation without transforming properties:
This means Carbon objects won’t be transformed into strings, and nested data objects won’t be transformed into arrays.

Advanced Transform Method

The transform method is highly configurable:
Output:

Disable Value Transformation

Output:

Disable Property Name Mapping

Enable Wrapping

Output:

Add Global Transformers

Transformation Depth

Prevent infinite loops in nested data structures by setting a maximum depth:

Global Configuration

In config/data.php:
Disable the check:
Throw exception or return empty array:

Per-Transformation

Set depth for a specific transformation:
Return empty array instead of throwing: