[8.x] Fix model serialization on anonymous components #39319
Merged
+75
−5
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.
Fixes #39232
When rendering anonymous components, we do not know which attributes passed to the components are going to be used as "props" (not sanitized) vs. "attributes" (sanitized since they are likely going to be rendered into the DOM directly). With class based components we do not have this issue since we can determine which attributes are actually props by looking at the properties on the class.
Therefore, when using anonymous components, we pass every attribute as both a prop and an attribute and then the
@props
directive removes the specified props from the$attributes
bag. However, in the process of passing everything as attributes, every object with a__toString
method gets escaped - I guess because we assumed they would be rendered in the DOM?Anyways, that is pretty undesirable in the case of Eloquent models and collections especially because the serialization process could be resource intensive if it loads additional relationships.
In order to try to solve this in a way that is as backwards-compatible as possible (in case people really are putting JSON serialized models into the DOM, I introduced a new
CanBeEscapedWhenConvertedToString
interface which models and collections can use.When the Blade attribute sanitization method encounters an object of this type, we will invoke the method defined by the contract which states that when this object is converted to a string it should be escaped. Therefore, if people really do try to render this object as a string it will still be escaped.
Would appreciate any feedback on this if anyone has a better idea or sees any downfalls with this approach.