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.