[5.5] [WIP] Eloquent object casting #18106
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a direct port Taylor's PR (#13706). Related "Internals" discussion is: laravel/ideas#9.
Object casting solves often requested features like:
$encrypts
property that encrypts model attributes #16457, [5.3] Offer an "Attribute Casting" of encrypt #16443)polygon
,enum
,cidr
,macaddr
Objects need to implement two methods (all 3 parameters are optional):
The method signatures are slightly different to #13706, because this PR passes the attribute key to both methods, in order to make objects reusable (so attribute keys don't have to be hard coded).
Objects can be set/updated as usual:
This however does not work:
You may of course add methods to objects:
User.php
Token.php
The token example touches a single model attributes and acts as a accessor/mutator.
Address.php
The address example touches multiple model attributes and has a
validate()
method for extra functionality.Json.php
The JSON example acts as a little helper to make it easier work with nested JSON data.