> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/spatie/laravel-data/llms.txt
> Use this file to discover all available pages before exploring further.

# Normalizers

> Transform various input types into arrays for data object creation

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:

```php theme={null}
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`:

```php theme={null}
'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:

```php theme={null}
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:

```php theme={null}
interface Normalizer
{
    public function normalize(mixed $value): null|array|Normalized;
}
```

### Example Implementation

```php theme={null}
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.

<Note>
  Magical creation methods always have precedence over normalizers.
</Note>
