Skip to content

Commit

Permalink
[9.x] Add a new function onlyTrashed (#44989)
Browse files Browse the repository at this point in the history
* Add a new function `onlyTrashed`

* Add test `onlyTrashed` in `ValidationUniqueRuleTest`

* Update DatabaseRule.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
michaelnabil230 and taylorotwell committed Nov 17, 2022
1 parent 64f11a3 commit 25c8fed
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Validation/Rules/DatabaseRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
11 changes: 11 additions & 0 deletions tests/Validation/ValidationExistsRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
11 changes: 11 additions & 0 deletions tests/Validation/ValidationUniqueRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 25c8fed

Please sign in to comment.