Skip to content

Commit

Permalink
PHPORM-68 Fix unique validator when the validated value is part of an…
Browse files Browse the repository at this point in the history
… existing value (#21)
  • Loading branch information
GromNaN authored and alcaeus committed Aug 22, 2023
1 parent 1d74dc3 commit d5f1bb9
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ All notable changes to this project will be documented in this file.
- Remove call to deprecated `Collection::count` for `countDocuments` [#18](https://github.com/GromNaN/laravel-mongodb-private/pull/18) by [@GromNaN](https://github.com/GromNaN).
- Accept operators prefixed by `$` in `Query\Builder::orWhere` [#20](https://github.com/GromNaN/laravel-mongodb-private/pull/20) by [@GromNaN](https://github.com/GromNaN).
- Remove `Query\Builder::whereAll($column, $values)`. Use `Query\Builder::where($column, 'all', $values)` instead. [#16](https://github.com/GromNaN/laravel-mongodb-private/pull/16) by [@GromNaN](https://github.com/GromNaN).
- Fix validation of unique values when the validated value is found as part of an existing value. [#21](https://github.com/GromNaN/laravel-mongodb-private/pull/21) by [@GromNaN](https://github.com/GromNaN).

## [3.9.2] - 2022-09-01

Expand Down
4 changes: 3 additions & 1 deletion src/Validation/DatabasePresenceVerifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Jenssegers\Mongodb\Validation;

use MongoDB\BSON\Regex;

class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVerifier
{
/**
Expand All @@ -17,7 +19,7 @@ class DatabasePresenceVerifier extends \Illuminate\Validation\DatabasePresenceVe
*/
public function getCount($collection, $column, $value, $excludeId = null, $idColumn = null, array $extra = [])
{
$query = $this->table($collection)->where($column, 'regex', '/'.preg_quote($value).'/i');
$query = $this->table($collection)->where($column, new Regex('^'.preg_quote($value).'$', '/i'));

if ($excludeId !== null && $excludeId != 'NULL') {
$query->where($idColumn ?: 'id', '<>', $excludeId);
Expand Down
6 changes: 6 additions & 0 deletions tests/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public function testUnique(): void
);
$this->assertFalse($validator->fails());

$validator = Validator::make(
['name' => 'John'], // Part of an existing value
['name' => 'required|unique:users']
);
$this->assertFalse($validator->fails());

User::create(['name' => 'Johnny Cash', 'email' => '[email protected]']);

$validator = Validator::make(
Expand Down

0 comments on commit d5f1bb9

Please sign in to comment.