From 9a302ff334b7f81d26f9249da0311e49291457a7 Mon Sep 17 00:00:00 2001 From: Caleb Porzio Date: Fri, 10 Jan 2020 09:30:38 -0500 Subject: [PATCH] [6.x] Add ->firstWhere eloquent method (#31089) * Add ->firstWhere eloquent method * Correct the docblock return signature --- src/Illuminate/Database/Eloquent/Builder.php | 14 ++++++++++ .../Database/EloquentWhereTest.php | 27 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index 02ba30fd06a2..7e2f57d8c4f2 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -235,6 +235,20 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' return $this; } + /** + * Add a basic where clause to the query, and return the first result. + * + * @param \Closure|string|array $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Model|static + */ + public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') + { + return $this->where($column, $operator, $value, $boolean)->first(); + } + /** * Add an "or where" clause to the query. * diff --git a/tests/Integration/Database/EloquentWhereTest.php b/tests/Integration/Database/EloquentWhereTest.php index 45416208c322..3600dc42d269 100644 --- a/tests/Integration/Database/EloquentWhereTest.php +++ b/tests/Integration/Database/EloquentWhereTest.php @@ -64,6 +64,33 @@ public function testWhereAndWhereOrBehavior() ) ); } + + public function testFirstWhere() + { + /** @var UserWhereTest $firstUser */ + $firstUser = UserWhereTest::create([ + 'name' => 'test-name', + 'email' => 'test-email', + 'address' => 'test-address', + ]); + + /** @var UserWhereTest $secondUser */ + $secondUser = UserWhereTest::create([ + 'name' => 'test-name1', + 'email' => 'test-email1', + 'address' => 'test-address1', + ]); + + $this->assertTrue($firstUser->is(UserWhereTest::firstWhere('name', '=', $firstUser->name))); + $this->assertTrue($firstUser->is(UserWhereTest::firstWhere('name', $firstUser->name))); + $this->assertTrue($firstUser->is(UserWhereTest::where('name', $firstUser->name)->firstWhere('email', $firstUser->email))); + $this->assertNull(UserWhereTest::where('name', $firstUser->name)->firstWhere('email', $secondUser->email)); + $this->assertTrue($firstUser->is(UserWhereTest::firstWhere(['name' => 'test-name', 'email' => 'test-email']))); + $this->assertNull(UserWhereTest::firstWhere(['name' => 'test-name', 'email' => 'test-email1'])); + $this->assertTrue($secondUser->is( + UserWhereTest::firstWhere(['name' => 'wrong-name', 'email' => 'test-email1'], null, null, 'or')) + ); + } } class UserWhereTest extends Model