> ## 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.

# Default Values

> Set default values for data object properties using constructors and class properties.

There are a few ways to define default values for a data object. Since a data object is just a regular PHP class, you can use the constructor to set default values:

```php theme={null}
class SongData extends Data
{
    public function __construct(
        public string $title = 'Never Gonna Give You Up',
        public string $artist = 'Rick Astley',
    ) {
    }
}
```

This works for simple types like strings, integers, floats, booleans, enums and arrays.

## Complex Default Values

But what if you want to set a default value for a more complex type like a `CarbonImmutable` object? You can use the constructor to do this:

```php theme={null}
class SongData extends Data
{
    #[Date]
    public CarbonImmutable|Optional $date;

    public function __construct(
        public string $title = 'Never Gonna Give You Up',
        public string $artist = 'Rick Astley',
    ) {
        $this->date = CarbonImmutable::create(1987, 7, 27);
    }
}
```

You can now do the following:

```php theme={null}
SongData::from();
SongData::from(['title' => 'Giving Up On Love', 'date' => CarbonImmutable::create(1988, 4, 15)]);
```

## Default Values with Validation

Even validation will work:

```php theme={null}
SongData::validateAndCreate();
SongData::validateAndCreate(['title' => 'Giving Up On Love', 'date' => CarbonImmutable::create(1988, 4, 15)]);
```

## Requirements for Complex Defaults

There are a few conditions for this approach:

<Steps>
  <Step title="Use a sole property">
    You must always use a sole property, a property within the constructor definition won't work
  </Step>

  <Step title="Add Optional type (recommended)">
    The optional type is technically not required, but it's a good idea to use it otherwise the validation won't work
  </Step>

  <Step title="Ensure valid defaults">
    Validation won't be performed on the default value, so make sure it is valid
  </Step>
</Steps>
