Description
Note: To see a solution for passing dynamic attributes to components, see the last comment.
- Laravel Version: 8.1.0
- PHP Version: PHP 7.4
- Database Driver & Version: irrelevant
Description:
Attributes passed to components as $attributes
are an instance of ComponentAttributeBag
.
This class has a property, $attributes
, that should be an array according to the source code.
However, @dd($attributes)
inside a component shows:
Illuminate\View\ComponentAttributeBag {#1284 ▼
#attributes: Illuminate\View\ComponentAttributeBag {#340 ▼
#attributes: array:1 [▼
"class" => "text-sm leading-5 font-medium text-gray-900"
]
}
}
As you can see, the outer CAB's $attributes
is another instance of CAB. The inner one is correct and has an array $attributes
property.
I've been looking into the source code trying to figure out how this can even happen — because most CAB's methods for setting $attributes
only accept arrays — but didn't succeed.
So, in short: I think $attributes
in components should be stored in a ComponentAttributeBag
's $attributes
property as an array. Not as another object which contains that array.
Steps To Reproduce:
Create a component and @dd($attributes)
inside.
Other implications
I discovered this by trying to create a ComponentAttributeBag
myself. My use case is that I have a dynamic component and I wanted to pass data from an array such that it would become part of $attributes`.
To do this, I tried to do:
<x-dynamic-component :component="$someVariable" {{ $field->attributes() }} class="abc">
Where $field->attributes()
returns new ComponentAttributeBag(['foo' => 'bar'])
.
However, this resulted in some errors in the compiled Blade code.
Since $attributes
can be used like
<input type="text" {{ $attributes }}>
I was hoping that creating a ComponentAttributeBag
— an object of the same type as $attributes
— would let me pass an array as attributes on an x-dynamic-component
call.
But, like I said, this resulted in those strange Blade errors. This might be due to the fact that a version of ComponentAttributeBag
which works — components' $attributes
— has a structure of ComponentAttributeBag->ComponentAttributeBag->array
, rather than ComponentAttributeBag->array
(which it should have), that I tried to construct myself.
So, to recapitulate, I'd like to know:
- If
$attributes
in components should beComponentAttributeBag->attributes = array
, rather than two nested objects - If the fact that
$attributes
uses two nested objects is why my ownComponentAttributeBag
is not working in<x-dynamic-component :component="$someVariable" {{ $field->attributes() }}>
Point 1 is a mismatch of docblocks and the real object, and point 2 is what I'm really trying to achieve.