Security Tip: Eloquent Casting to HtmlString!

[Tip #114] One of my favourite Laravel features, the humble HtmlString, is now available as an Eloquent Cast - which should make it much more accessible! 🎉 But there is a catch... 😟

Security Tip: Eloquent Casting to HtmlString!

Long-time readers will be well aware how much I love the HtmlString helper class in Laravel. It's an important way to prevent Cross-Site Scripting (XSS) from sneaking into your apps.

💡
For those unfamiliar with the class, the HtmlString class (\Illuminate\Support\HtmlString) provides a way for you to identify a string as HTML and prevent Blade's escaped tags ({{ ... }}) from escaping the string - keeping your Blade free of potentially dangerous {!! ... !!} tags. Learn more here...

The only downside of HtmlString is that you need to manually wrap your content, however, thanks to a Pull Request from Ralph J. Smit, you can now automatically cast attributes as HtmlString:

protected function casts(): array
{
   return [
      'html' => AsHtmlString::class,
   ];
}

And then use them directly inside your Blade templates:

<div>
  {{ $model->html }}
</div>

This is available in Laravel v12.4, and looks like it will save a bit of boilerplate when working with HTML strings.

⚠️ But wait a sec...

I would be remiss if I didn't point out the massive security risk with using this cast! This cast means whatever is stored in the database will be rendered without being escaped - typically rendered as HTML. If the user has any control over this content, they could easily inject some XSS and hijack your app.

That said, this is the same risk as using HtmlString manually - but using the cast potentially hides the fact that the string is being rendered as HTML. This could result in developers not being aware the attributes they are sending user-data into aren't going to be escaped.

So if you're going to use this cast, make sure you properly name and document it - so you and your team aren't going to accidently open up some XSS. Which, to be fair, is what you need to do any time you're using HtmlString.

In other words... be intentional when using tools with sharp edges like HtmlString, especially around user data.


Securing Laravel is SPONSORED by...

Want to see your brand here?

Find out more...

If you found this security tip useful, subscribe to get weekly Security Tips straight to your inbox. Upgrade to a premium subscription for exclusive monthly In Depth articles, or drop a coin in the tip jar to show your support.

When was the last time you had a penetration test? Book a Laravel Security Audit and Penetration Test, or a budget-friendly Security Review!

You can also connect with me on Bluesky, or other socials, and check out Practical Laravel Security, my interactive course designed to boost your Laravel security skills.