Skip to content

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
mohammad-fouladgar pushed a commit to mohammad-fouladgar/framework that referenced this pull request Jul 22, 2025
…56159) * Add support for passing `Htmlable` instance to `Js::from()` * Reorder import for styling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants