From 25c8fed2c54d6967e16c99a21ddae0e2a73d3f20 Mon Sep 17 00:00:00 2001 From: Michael Nabil <46572405+michaelnabil230@users.noreply.github.com> Date: Thu, 17 Nov 2022 16:31:19 +0200 Subject: [PATCH] [9.x] Add a new function `onlyTrashed` (#44989) * Add a new function `onlyTrashed` * Add test `onlyTrashed` in `ValidationUniqueRuleTest` * Update DatabaseRule.php Co-authored-by: Taylor Otwell --- src/Illuminate/Validation/Rules/DatabaseRule.php | 13 +++++++++++++ tests/Validation/ValidationExistsRuleTest.php | 11 +++++++++++ tests/Validation/ValidationUniqueRuleTest.php | 11 +++++++++++ 3 files changed, 35 insertions(+) diff --git a/src/Illuminate/Validation/Rules/DatabaseRule.php b/src/Illuminate/Validation/Rules/DatabaseRule.php index bac373634549..c523bec6c537 100644 --- a/src/Illuminate/Validation/Rules/DatabaseRule.php +++ b/src/Illuminate/Validation/Rules/DatabaseRule.php @@ -182,6 +182,19 @@ public function withoutTrashed($deletedAtColumn = 'deleted_at') return $this; } + /** + * Only include soft deleted models during the existence check. + * + * @param string $deletedAtColumn + * @return $this + */ + public function onlyTrashed($deletedAtColumn = 'deleted_at') + { + $this->whereNotNull($deletedAtColumn); + + return $this; + } + /** * Register a custom query callback. * diff --git a/tests/Validation/ValidationExistsRuleTest.php b/tests/Validation/ValidationExistsRuleTest.php index 561ef227eb88..bf4654532f78 100644 --- a/tests/Validation/ValidationExistsRuleTest.php +++ b/tests/Validation/ValidationExistsRuleTest.php @@ -234,6 +234,17 @@ public function testItIgnoresSoftDeletes() $this->assertSame('exists:table,NULL,softdeleted_at,"NULL"', (string) $rule); } + public function testItOnlyTrashedSoftDeletes() + { + $rule = new Exists('table'); + $rule->onlyTrashed(); + $this->assertSame('exists:table,NULL,deleted_at,"NOT_NULL"', (string) $rule); + + $rule = new Exists('table'); + $rule->onlyTrashed('softdeleted_at'); + $this->assertSame('exists:table,NULL,softdeleted_at,"NOT_NULL"', (string) $rule); + } + protected function createSchema() { $this->schema('default')->create('users', function ($table) { diff --git a/tests/Validation/ValidationUniqueRuleTest.php b/tests/Validation/ValidationUniqueRuleTest.php index cea86c7e11c6..69212ab4063e 100644 --- a/tests/Validation/ValidationUniqueRuleTest.php +++ b/tests/Validation/ValidationUniqueRuleTest.php @@ -92,6 +92,17 @@ public function testItIgnoresSoftDeletes() $rule->withoutTrashed('softdeleted_at'); $this->assertSame('unique:table,NULL,NULL,id,softdeleted_at,"NULL"', (string) $rule); } + + public function testItOnlyTrashedSoftDeletes() + { + $rule = new Unique('table'); + $rule->onlyTrashed(); + $this->assertSame('unique:table,NULL,NULL,id,deleted_at,"NOT_NULL"', (string) $rule); + + $rule = new Unique('table'); + $rule->onlyTrashed('softdeleted_at'); + $this->assertSame('unique:table,NULL,NULL,id,softdeleted_at,"NOT_NULL"', (string) $rule); + } } class EloquentModelStub extends Model