[5.8] Add less greedy mutator #29375
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.
Scenario
I have a
Product
that comes in multiple colors. Available colors are defined as a JSON field on theproducts
table. I cast the colors to aCollection
in the model.My CRUD forms use a
<textarea>
to accept a comma separated list of colors. When that data is submitted to my controller, I need toexplode
and thentrim
the colors.This is okay, but we can see we're duplicating some code here. If we could move the trimming (and maybe even the exploding if you like) into the Model, we would have 1 point of transformation for this data.
We could try to add a mutator to our model:
but due to the greediness of the mutator (https://github.com/laravel/framework/blob/5.8/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L571), we would need to reimplement the casting logic ourselves.
Proposed Solution
This PR allows us to bypass this greediness with a slightly modified mutator method.
Since we are returning a value here, the Model can now continue to perform its normal casting logic after we are done with any changes we want to make to the input.
If you wanted to be so bold, you could even go a step further and accept both
array
and comma separatedstring
inputs:Definitely open to naming suggestion here. Will add tests if there's interest in the feature.
Would also be curious to know if the mutators were originally made this greedy intentionally. Didn't have any luck finding info from old commits. If it wasn't intentional, maybe we discuss making the default be not greedy?