Skip to content

Commit 668d625

Browse files
[7.x] Fix not being able to set component attributes from inside class (#31676)
* Made attributes merge instead of overwrite * Added test for attribute merging
1 parent 7efc657 commit 668d625

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/Illuminate/View/Component.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ public function withAttributes(array $attributes)
214214
{
215215
$this->attributes = $this->attributes ?: new ComponentAttributeBag;
216216

217-
$this->attributes->setAttributes($attributes);
217+
$this->attributes = $this->attributes->merge($attributes);
218218

219219
return $this;
220220
}

tests/View/ViewComponentTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ public function testPublicMethodsWithNoArgsAreEagerlyInvokedAndNotCached()
4545
$component->data();
4646
$this->assertEquals(3, $component->counter);
4747
}
48+
49+
public function testAttributesAreMergedNotOverwritten()
50+
{
51+
$component = new TestDefaultAttributesComponent;
52+
53+
$this->assertEquals('text-red-500', $component->attributes->get('class'));
54+
55+
$component->withAttributes(['class' => 'bg-blue-100']);
56+
57+
$this->assertEquals('bg-blue-100 text-red-500', $component->attributes->get('class'));
58+
}
4859
}
4960

5061
class TestViewComponent extends Component
@@ -99,3 +110,16 @@ private function privateHello()
99110
$this->counter++;
100111
}
101112
}
113+
114+
class TestDefaultAttributesComponent extends Component
115+
{
116+
public function __construct()
117+
{
118+
$this->withAttributes(['class' => 'text-red-500']);
119+
}
120+
121+
public function render()
122+
{
123+
return $this->attributes->get('id');
124+
}
125+
}

0 commit comments

Comments
 (0)