Normalizers transform payloads (like models, objects, or JSON) into arrays that can be used in the data pipeline.
Usage Example
Create a data object from an Eloquent model:
SongData::from(Song::findOrFail($id));
The normalizer converts the model into an array before it enters the pipeline.
Default Normalizers
Five normalizers are enabled by default:
- ModelNormalizer - Casts Eloquent models
- ArrayableNormalizer - Casts
Arrayable objects
- ObjectNormalizer - Casts
stdObject instances
- ArrayNormalizer - Casts arrays
- JsonNormalizer - Casts JSON strings
Optional Normalizer
- FormRequestNormalizer - Normalizes form requests by calling the
validated() method
Configuration
Configure normalizers globally in config/data.php:
'normalizers' => [
Spatie\LaravelData\Normalizers\ModelNormalizer::class,
Spatie\LaravelData\Normalizers\ArrayableNormalizer::class,
Spatie\LaravelData\Normalizers\ObjectNormalizer::class,
Spatie\LaravelData\Normalizers\ArrayNormalizer::class,
Spatie\LaravelData\Normalizers\JsonNormalizer::class,
],
Per-Data-Class Configuration
Override normalizers for a specific data class:
class SongData extends Data
{
public function __construct(
// ...
) {
}
public static function normalizers(): array
{
return [
ModelNormalizer::class,
ArrayableNormalizer::class,
ObjectNormalizer::class,
ArrayNormalizer::class,
JsonNormalizer::class,
];
}
}
Creating a Normalizer
Implement the Normalizer interface:
interface Normalizer
{
public function normalize(mixed $value): null|array|Normalized;
}
Example Implementation
class ArrayableNormalizer implements Normalizer
{
public function normalize(mixed $value): ?array
{
if (! $value instanceof Arrayable) {
return null;
}
return $value->toArray();
}
}
Return Value
- Return an array if the normalizer can normalize the payload
- Return null if the normalizer cannot handle the payload
Execution Order
Normalizers execute in the order defined. The first normalizer that doesn’t return null is used.
Magical creation methods always have precedence over normalizers.