Skip to content
This repository was archived by the owner on Aug 22, 2023. It is now read-only.

PHPORM-68 Fix unique validator when the validated value is part of an existing value #21

Merged
merged 1 commit into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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' => 'johnny.cash+200@gmail.com']);

$validator = Validator::make(
Expand Down