Description
- Laravel Version: 8.64.0
- PHP Version: 8.0.11
Description
This blog post explains the issue nicely, so I'm basically just copying it here. Hope you don't mind, @hbgl!
Take a look at this anonymous component:
<!-- post-title.blade.php -->
@props(['post'])
<h1 {{ $attributes }}>{{ $post->title }}</h1>
And here is how it is used in, say, a post list page:
@foreach ($posts $post)
<x-post-title :post="$post" />
@endforeach
In this example, the posts are Eloquent models that were previously loaded from the database. Now, if you run this code, you will notice nothing strange in particular. Everything works as intended. However, if you dig a little deeper, you will find some unexpected behavior:
Every time the component is instantiated, the post model is being serialized to JSON.
The cause for this behavior lies in the way the Blade component compiler processes attributes inside the sanitizeComponentAttribute
function.
// CompilesComponents.php
public static function sanitizeComponentAttribute($value)
{
return is_string($value) ||
(is_object($value) && ! $value instanceof ComponentAttributeBag && method_exists($value, '__toString'))
? e($value)
: $value;
}
Basically, any object that implements a __toString
function will be converted to a string. In the case of an Eloquent model, this will convert it to JSON. Depending on how large your model is and how often the component is used, this will waste a significant amount of resources on constructing JSON strings that are never used.
In the blog post, @hbgl goes on to describe a solution: use a class based component and add your props to the constructor arguments. After you do that, your objects will no longer be converted to strings.
However, I think this bug is worth fixing. In my project I use a lot of anonymous components and my app's performance is suffering pretty significantly from this bug. While I may well go down the road of converting them into classes, I think this bug really limits the real-world utility and scalability of anonymous components.
I don't have a good solution in mind – my understanding of the internals here is too limited. But I do wonder, since props are defined at the top of each anonymous component's template, is there some way to read those in advance and then prevent them from being sanitized and passed into the AttributeBag?
Note: This issue is not the same as #34346, where props being passed into dynamic components were being HTML-encoded. This issue is about anonymous components and still persists.