News

Eloquent Cast for HTML Strings in Laravel

Published
Eloquent Cast for HTML Strings in Laravel image

Release updates

Never miss a Laravel release

Get an email whenever a new Laravel release lands.

As of v12.4, you can automatically cast Eloquent attributes to an HTML string using the AsHtmlString cast. The framework already has an HtmlString class available; this cast stitches it together with Eloquent attributes that you can use where appropriate:

use Illuminate\Database\Eloquent\Casts\AsHtmlString;
 
protected function casts(): array
{
return [
'myAttribute' => AsHtmlString::class,
];
}
 
// Using the cast automatically does this
$model->myAttribute; // \Illuminate\Support\HtmlString

Before this cast, you would either need to define your own custom cast, define an accessor, or manually create an HtmlString instance:

protected function html(): Attribute
{
return Attribute::make(
get: fn (string $value) => str($value)->toHtmlString(),
);
}
 
// Using the html() accessor
$model->html; // HtmlString
 
// Or manually
$myString = new HtmlString($model->myString);
$myString = str($model->myString)->toHtmlString();

While the AsHtmlString is probably a narrow use case, it allows you to use the HTML string from your model when rendering dynamic content from your database. Of course, ensure that you consider your use case carefully, as HtmlString instances are not escaped in Blade, for example:

{{-- Warning: not be escaped when rendered in blade templates! --}}
{{ $model->html }}

There might be other niche use cases where HtmlString can be helpfulul cast—you'll know when you need it—but use caution.

See the attribute casting documentation for details on how to cast your model attributes.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Image Dominant Color and HEIC Support in Laravel 13.24 image

Image Dominant Color and HEIC Support in Laravel 13.24

Read article
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article
PhpStorm 2026.2 Released image

PhpStorm 2026.2 Released

Read article
Laravel Doctor: Diagnose Your App With One Artisan Command image

Laravel Doctor: Diagnose Your App With One Artisan Command

Read article
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article