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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article