Skip to content

[12.x] Add whereIf() method to Eloquent Builder #54810

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 1 commit 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
14 changes: 14 additions & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,20 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

/**
* Apply a "where" condition if the given condition is true.
*
* @param bool $condition
* @param string $column
* @param string $operator
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Builder
*/
public function whereIf($condition, $column, $operator = '=', $value = null)
{
return $condition ? $this->where($column, $operator, $value) : $this;
}

/**
* Add a basic where clause to the query, and return the first result.
*
Expand Down
32 changes: 32 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2642,6 +2642,38 @@ protected function getMockQueryBuilder()

return $query;
}

public function testWhereIfAppliesConditionWhenTrue()
{
$builder = $this->getMockBuilder(Builder::class)
->disableOriginalConstructor()
->onlyMethods(['where'])
->getMock();

$builder->expects($this->once())
->method('where')
->with('foo', '=', 'bar')
->willReturnSelf();

$result = $builder->whereIf(true, 'foo', '=', 'bar');

$this->assertSame($builder, $result);
}

public function testWhereIfDoesNotApplyConditionWhenFalse()
{
$builder = $this->getMockBuilder(Builder::class)
->disableOriginalConstructor()
->onlyMethods(['where'])
->getMock();

$builder->expects($this->never())
->method('where');

$result = $builder->whereIf(false, 'foo', '=', 'bar');

$this->assertSame($builder, $result);
}
}

class EloquentBuilderTestStub extends Model
Expand Down
Loading