Skip to content

Commit 1615524

Browse files
[12.x] clarify how to "set" value objects with custom casts (#10342)
* clarify how to "set" value objects with custom casts 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. * Update eloquent-mutators.md --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 9ec5d7e commit 1615524

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

eloquent-mutators.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -736,7 +736,7 @@ class User extends Model
736736
<a name="value-object-casting"></a>
737737
### Value Object Casting
738738

739-
You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, the `set` method should return an array of key / value pairs that will be used to set raw, storable values on the model.
739+
You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, if your value object encompasses more than one database column, the `set` method must return an array of key / value pairs that will be used to set raw, storable values on the model. If your value object only affects a single column, you should simply return the storable value.
740740

741741
As an example, we will define a custom cast class that casts multiple model values into a single `Address` value object. We will assume the `Address` value has two public properties: `lineOne` and `lineTwo`:
742742

0 commit comments

Comments
 (0)