Skip to content

Commit 8d93cf2

Browse files
committed
feat: Add firstCaseInsensitive method to EntityControlTrait
1 parent 3fc6180 commit 8d93cf2

3 files changed

Lines changed: 41 additions & 0 deletions

File tree

src/Traits/EntityControlTrait.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,17 @@ public function findBy(string $field, $value): ?Model
290290
return $this->first([$field => $value]);
291291
}
292292

293+
public function firstCaseInsensitive(string $field, string $value): ?Model
294+
{
295+
$result = $this->getQuery()
296+
->whereRaw("LOWER({$field}) = ?", [strtolower($value)])
297+
->first();
298+
299+
$this->postQueryHook();
300+
301+
return $result;
302+
}
303+
293304
public function find($id): ?Model
294305
{
295306
return $this->first($id);

tests/EntityControlTraitTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,21 @@ public function testFindBy()
750750
$this->assertSettablePropertiesReset(self::$testRepositoryClass);
751751
}
752752

753+
public function testFirstCaseInsensitive()
754+
{
755+
$this->mockFirstCaseInsensitive(self::$selectResult, 'john@example.com');
756+
757+
self::$testRepositoryClass
758+
->withTrashed()
759+
->onlyTrashed()
760+
->force()
761+
->with('relation')
762+
->withCount('relation')
763+
->firstCaseInsensitive('email', 'JOHN@example.com');
764+
765+
$this->assertSettablePropertiesReset(self::$testRepositoryClass);
766+
}
767+
753768
public function testFindByEmptyResult()
754769
{
755770
$this->mockSelectById(

tests/support/Traits/SqlMockTrait.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,21 @@ protected function mockFirstBy(array $selectResult): void
7070
);
7171
}
7272

73+
protected function mockFirstCaseInsensitive(array $selectResult, string $value): void
74+
{
75+
$this->mockSelect(
76+
'select "test_models".*, (select count(*) from "relation_models" '
77+
. 'where "test_models"."id" = "relation_models"."test_model_id") as "relation_count" '
78+
. 'from "test_models" where "test_models"."deleted_at" is not null and LOWER(email) = ? limit 1',
79+
$selectResult,
80+
[$value],
81+
);
82+
83+
$this->mockSelect(
84+
'select * from "relation_models" where "relation_models"."test_model_id" in (1)',
85+
);
86+
}
87+
7388
protected function mockLast(array $selectResult): void
7489
{
7590
$this->mockSelectById(

0 commit comments

Comments
 (0)