diff --git a/src/Attributes.php b/src/Attributes.php index e253ced..01f07a8 100644 --- a/src/Attributes.php +++ b/src/Attributes.php @@ -22,7 +22,7 @@ class Attributes */ public function setAttribute(string $name, mixed $value = null): self { - if ($value === null) { + if ($value === null || $value === false) { unset($this->attributes[$name]); return $this; } diff --git a/src/BaseItem.php b/src/BaseItem.php index 24f7c9e..b6411b9 100644 --- a/src/BaseItem.php +++ b/src/BaseItem.php @@ -160,9 +160,9 @@ public function placeholder(string $placeholder): static * @param bool $required * @return static */ - public function required(bool $required): static + public function required(bool $required = true): static { - $this->attributes->setAttribute('required', $required); + $this->attributes->setAttribute('required', $required ? 'required' : null); return $this; } @@ -216,6 +216,20 @@ public function attribute(string|int $name, ?string $value = null): static return $this; } + /** + * @description Set the attributes of the element + * @param array $attributes + * @return static + */ + public function setAttributes(array $attributes): static + { + foreach ($attributes as $name => $value) { + $this->attributes->setAttribute($name, $value); + } + + return $this; + } + public function toHtml(): string { if ($this->hasError() && config('laravel-form.errors.enabled', false)) { diff --git a/tests/FormInputTest.php b/tests/FormInputTest.php index c94a786..286c290 100644 --- a/tests/FormInputTest.php +++ b/tests/FormInputTest.php @@ -90,10 +90,31 @@ public function testCanCreateInputWithCustomType(): void $this->assertEquals('', $item); } - public function testCanCreateInputWithoutType() + public function testCanCreateInputWithoutType(): void { $item = LaravelForm::input()->type(null); $this->assertEquals('', $item); } + + public function testCanCreateInputWithAttributes(): void + { + $item = LaravelForm::input()->setAttributes(['type' => 'password', 'name' => 'password']); + + $this->assertEquals('', $item); + } + + public function testCanCreateInputWithRequired(): void + { + $item = LaravelForm::input()->required(); + + $this->assertEquals('', $item); + } + + public function testCanCreateInputWithoutRequired(): void + { + $item = LaravelForm::input()->required()->required(false); + + $this->assertEquals('', $item); + } }