diff --git a/src/HelpersServiceProvider.php b/src/HelpersServiceProvider.php index fe77fe2..50564f9 100755 --- a/src/HelpersServiceProvider.php +++ b/src/HelpersServiceProvider.php @@ -67,7 +67,6 @@ protected function extendValidator(): void }); Validator::extend('list_exists', function ($attribute, $value, $parameters) { - if (count($parameters) < 1) { return false; } @@ -76,12 +75,17 @@ protected function extendValidator(): void $keyField = Arr::get($parameters, 1, 'id'); if (!empty(Arr::get($parameters, 2))) { - $value = collect($value)->pluck(Arr::get($parameters, 2)); + $value = Arr::pluck($value, Arr::get($parameters, 2)); } - return DB::table($table) + $value = array_unique($value); + + $existingValueCount = DB::table($table) ->whereIn($keyField, $value) - ->exists(); + ->distinct() + ->count($keyField); + + return $existingValueCount === count($value); }); } diff --git a/tests/ValidatorTest.php b/tests/ValidatorTest.php index 91cbb90..e0282a8 100644 --- a/tests/ValidatorTest.php +++ b/tests/ValidatorTest.php @@ -67,7 +67,7 @@ public function testUniqueExceptOfAuthorizedUserFail() public function testListExists() { - $this->mockListExists(true); + $this->mockListExists([1, 2, 3]); $validator = Validator::make( ['ids' => [1, 2, 3]], @@ -77,9 +77,22 @@ public function testListExists() $this->assertTrue($validator->passes()); } + public function testListExistsIfDuplicateValues() + { + $this->mockListExists([1, 2, 3]); + + $validator = Validator::make([ + 'ids' => [1, 2, 3, 3], + ], [ + 'ids' => 'list_exists:clients,user_id', + ]); + + $this->assertTrue($validator->passes()); + } + public function testListExistsByArray() { - $this->mockListExists(true); + $this->mockListExists([1, 2, 3]); $validator = Validator::make( [ @@ -108,7 +121,7 @@ public function testListExistsByArray() public function testListExistsFailedValidation() { - $this->mockListExists(false); + $this->mockListExists([1, 2]); $validator = Validator::make( ['ids' => [1, 2, 3]], diff --git a/tests/support/Traits/SqlMockTrait.php b/tests/support/Traits/SqlMockTrait.php index 59ec754..8016121 100644 --- a/tests/support/Traits/SqlMockTrait.php +++ b/tests/support/Traits/SqlMockTrait.php @@ -432,14 +432,14 @@ protected function mockExistsUsersExceptAuthorizedByArray( } protected function mockListExists( - bool $isExist, + array $result, string $table = 'clients', string $keyField = 'user_id', ): void { - $this->mockSelectExists( - "select exists(select * from \"{$table}\" where \"{$keyField}\" in (?, ?, ?)) as \"exists\"", - $isExist, - [1, 2, 3] + $this->mockSelect( + query: "select count(distinct \"{$keyField}\") as aggregate from \"{$table}\" where \"{$keyField}\" in (?, ?, ?)", + result: [[ 'aggregate' => count($result) ]], + bindings: [1, 2, 3], ); }