From 912c51b5812838391d4d779bdeb8984af8c00d6e Mon Sep 17 00:00:00 2001 From: Ruben Van Assche Date: Tue, 2 Nov 2021 14:58:31 +0100 Subject: [PATCH] Update ignore rule to accept a closure --- docs/advanced-usage/validation-attributes.md | 3 +++ docs/as-a-data-transfer-object/request-to-data-object.md | 4 ++-- src/Attributes/Validation/Unique.php | 7 +++++-- tests/Attributes/Validation/RulesTest.php | 5 +++++ 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/advanced-usage/validation-attributes.md b/docs/advanced-usage/validation-attributes.md index f08ff1bb..0aec6b19 100644 --- a/docs/advanced-usage/validation-attributes.md +++ b/docs/advanced-usage/validation-attributes.md @@ -850,6 +850,9 @@ public string $value; #[Unique('users', ignore: 5)] public string $value; + +#[Unique('users', ignore: fn() => request()->get('email'))] +public string $value; ``` ### Url diff --git a/docs/as-a-data-transfer-object/request-to-data-object.md b/docs/as-a-data-transfer-object/request-to-data-object.md index ec0206d1..50518ee0 100644 --- a/docs/as-a-data-transfer-object/request-to-data-object.md +++ b/docs/as-a-data-transfer-object/request-to-data-object.md @@ -143,8 +143,8 @@ class SongData extends Data public static function fromRequest(Request $request): static { return new self( - {$request->input('title_of_song')}, - {$request->input('artist_name')} + $request->input('title_of_song'), + $request->input('artist_name') ); } } diff --git a/src/Attributes/Validation/Unique.php b/src/Attributes/Validation/Unique.php index a14cbaa0..2d3037be 100644 --- a/src/Attributes/Validation/Unique.php +++ b/src/Attributes/Validation/Unique.php @@ -13,7 +13,7 @@ public function __construct( private string $table, private ?string $column = 'NULL', private ?string $connection = null, - private ?string $ignore = null, + private string|Closure|null $ignore = null, private ?string $ignoreColumn = null, private bool $withoutTrashed = false, private string $deletedAtColumn = 'deleted_at', @@ -33,7 +33,10 @@ public function getRules(): array } if ($this->ignore) { - $rule->ignore($this->ignore, $this->ignoreColumn); + $rule->ignore( + is_callable($this->ignore) ? ($this->ignore)() : $this->ignore, + $this->ignoreColumn + ); } if ($this->where) { diff --git a/tests/Attributes/Validation/RulesTest.php b/tests/Attributes/Validation/RulesTest.php index f8167a33..6ee20b34 100644 --- a/tests/Attributes/Validation/RulesTest.php +++ b/tests/Attributes/Validation/RulesTest.php @@ -979,6 +979,11 @@ public function uniqueAttributesDataProvider(): Generator 'expected' => [(new BaseUnique('users', 'email'))->ignore(5, 'uuid')], ]; + yield [ + 'attribute' => new Unique('users', 'email', ignore: fn() => 5), + 'expected' => [(new BaseUnique('users', 'email'))->ignore(5)], + ]; + $closure = fn (Builder $builder) => $builder; yield [