Skip to content

[12.x] Support Passing Htmlable Instances to Js::from() #56159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 28, 2025

Conversation

jj15asmr
Copy link
Contributor

@jj15asmr jj15asmr commented Jun 27, 2025

This PR adds support for passing Htmlable instances to the Js::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:

use Illuminate\Support\{HtmlString, Js};

$data = new HtmlString('<p>Hello, World!</p>');

echo Js::from($data);

// Output: "{}"

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 of Htmlable and if so, call the ->toHtml() method on it before encoding. This now gives us the expected result:

use Illuminate\Support\{HtmlString, Js};

$data = new HtmlString('<p>Hello, World!</p>');

echo Js::from($data);

// Output: "'\u003Cp\u003EHello, World!\u003C\/p\u003E'"

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.

@taylorotwell taylorotwell merged commit 9eac15d into laravel:12.x Jun 28, 2025
60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants