Skip to content

[11.x] Introduce whenWhere methods in query builder #53303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
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
33 changes: 33 additions & 0 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1773,6 +1773,39 @@ protected function addDateBasedWhere($type, $column, $operator, $value, $boolean
return $this;
}

/**
* Add a whenWhere to the query.
*
* @param mixed $condition
* @param string $column
* @param string|null $operator
* @param mixed|null $value
* @param string $boolean
* @return $this
*/
public function whenWhere($condition, $column, $operator = null, $value = null, string $boolean = 'and')
{
if (! $condition) {
return $this;
}

return $this->where($column, $operator, $value, $boolean);
}

/**
* Add a or whenWhere to the query.
*
* @param mixed $condition
* @param string $column
* @param string|null $operator
* @param mixed|null $value
* @return $this
*/
public function orWhenWhere($condition, $column, $operator = null, $value = null)
{
return $this->whenWhere($condition, $column, $operator, $value, 'or');
}

/**
* Add a nested where statement to the query.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Integration/Database/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,18 @@ public function testChunkMap()
$this->assertCount(3, DB::getQueryLog());
}

public function testWhenWhere()
{
$this->assertSame(1, DB::table('posts')->whenWhere(true, 'id', 1)->count());
$this->assertSame(2, DB::table('posts')->whenWhere(false, 'id', 1)->count());
}

public function testOrWhenWhere()
{
$this->assertSame(1, DB::table('posts')->whenWhere(true, 'id', 1)->count());
$this->assertSame(2, DB::table('posts')->whenWhere(false, 'id', 1)->count());
}

public function testPluck()
{
// Test SELECT override, since pluck will take the first column.
Expand Down