Skip to content

[12.x] clarify how to "set" value objects with custom casts #10342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 23, 2025

Conversation

browner12
Copy link
Contributor

the current wording only accounts for 1 of the 2 scenarios that can occur when using a custom cast with a value object. that Value Object can encompasses either 1 or many values on the model.

the current documentation addresses the example of an Address, which would have multiple fields like "line1", "line2", "city", etc. this set method should return the array as currently documented.

an example of a single value Value Object would be a phone number. a user might want it as an value object rather than a raw number to encapsulate behavior. this set method should return a string.

there is one distinct advantage to returning a string vs an array. it prevents the cast from being tied to explicit model field names. this allows a field of any name to use the cast:

'phone' => AsPhone::class,
'telephone' => AsPhone::class,

if a user returns an array from this simple 1 value cast, the cast loses its flexibility and the above example does not work.

browner12 and others added 2 commits April 23, 2025 11:33
the current wording only accounts for 1 of the 2 scenarios that can occur when using a custom cast with a value object. that Value Object can encompasses either 1 or many values on the model.

the current documentation addresses the example of an `Address`, which would have multiple fields like "line1", "line2", "city", etc.  this `set` method should return the array as currently documented.

an example of a single value Value Object would be a phone number. a user might want it as an value object rather than a raw number to encapsulate behavior. this `set` method should return a string.

there is one distinct advantage to returning a string vs an array. it prevents the cast from being tied to explicit model field names. this allows a field of any name to use the cast:

```php
'phone' => AsPhone::class,
'telephone' => AsPhone::class,
```

if a user returns an array from this simple 1 value cast, the cast loses its flexibility and the above example does not work.
@taylorotwell taylorotwell merged commit 1615524 into laravel:12.x Apr 23, 2025
@browner12 browner12 deleted the AB-casting-value-objects branch April 23, 2025 17:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants