[12.x] Support Passing Htmlable
Instances to Js::from()
#56159
Merged
+18
−0
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 PR adds support for passing
Htmlable
instances to theJs::from()
method. This change also affects the@js()
Blade directive as it uses the same underlying method.Previously, passing an
Htmlable
instance would result in an empty JSON object being returned:This is due to PHP's native
json_encode()
function not understanding how to convert the instance to a type it can work with (string, in this case).To fix this, we check if
$data
is an instance ofHtmlable
and if so, call the->toHtml()
method on it before encoding. This now gives us the expected result:I thought this would be useful as I recently needed to pass some sanitized HTML returned as an instance of
HtmlString
to an Alpine.js component. It removes the extra step of having to call->toHtml()
directly, making the conversion much more seamless.