[5.6] Cast model attribute to any class#24059
[5.6] Cast model attribute to any class#24059Whyounes wants to merge 3 commits intolaravel:5.6from Whyounes:5.6
Conversation
|
Casting model attributes to classes PRs raised couple of times already, but all the time they were rejected. This will be useful to create Value Objects. |
|
How is this attempt better than anything previously attempted?
|
|
I wasn't following all the previous propositions. This is just something I did a couple times in a Laravel app and I thought it could be useful to have out of the box instead of falling back to mutators.
|
|
@Whyounes My implementation of something similar can be found at https://github.com/hnhdigital-os/laravel-model-schema It's more than just attribute casting though, I've worked in a different approach to casts/hidden etc into a single schema array. |
|
@RoccoHoward I think this custom cast should be in the core. It's just one step from what we already have! |
So I would use these changes to point to a factory class instead of the value object?
A model attribute, yes, but not a value object. Money consists of a number and a currency. An Address consists of street name, zip code, city, and other attributes. Even a parsed email address can have two attributes; the actual email address and the display name.
I disagree with two points. I think this PR is incomplete without supporting the reverse, even it it were only for single-attribute value objects. And calling toString wouldn't really work if the value being wrapped was a non-string value, like an array or floating point number. |
|
If you're interesting in catching up on previous discussions, start at #18229 |
Currently, you can cast a model attribute to a primitive type or JSON. This PR will let model attributes to cast to any class. Here's an example: