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

# Optional Properties

> Handle optional properties in data objects for partial updates and flexible data structures.

Sometimes you have a data object with properties which shouldn't always be set, for example in a partial API update where you only want to update certain fields. In this case you can make a property `Optional` as such:

```php theme={null}
use Spatie\LaravelData\Optional;

class SongData extends Data
{
    public function __construct(
        public string $title,
        public string|Optional $artist,
    ) {
    }
}
```

You can now create the data object as such:

```php theme={null}
SongData::from([
    'title' => 'Never gonna give you up'
]);
```

The value of `artist` will automatically be set to `Optional`. When you transform this data object to an array, it will look like this:

```php theme={null}
[
    'title' => 'Never gonna give you up'
]
```

<Note>
  Optional properties are automatically excluded from the array representation when they are not set.
</Note>

## Manual Optional Values

You can manually use `Optional` values within magical creation methods as such:

```php theme={null}
class SongData extends Data
{
    public function __construct(
        public string $title,
        public string|Optional $artist,
    ) {
    }
    
    public static function fromTitle(string $title): static
    {
        return new self($title, Optional::create());
    }
}
```

## Converting Optional to Null

It is possible to automatically update `Optional` values to `null`:

```php theme={null}
class SongData extends Data {
    public function __construct(
        public string $title,
        public Optional|null|string $artist,
    ) {
    }
}

SongData::factory()
    ->withoutOptionalValues()
    ->from(['title' => 'Never gonna give you up']); // artist will `null` instead of `Optional`
```

<Note>
  You can read more about this [here](/as-a-dto/factories#disabling-optional-values).
</Note>
