Skip to content

Commit

Permalink
[6.x] Add ->firstWhere eloquent method (#31089)
Browse files Browse the repository at this point in the history
* Add ->firstWhere eloquent method

* Correct the docblock return signature
  • Loading branch information
calebporzio authored and taylorotwell committed Jan 10, 2020
1 parent b9e33b8 commit 9a302ff
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
27 changes: 27 additions & 0 deletions tests/Integration/Database/EloquentWhereTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9a302ff

Please sign in to comment.