Skip to content

Commit 6cf003a

Browse files
tomschlicktaylorotwell
authored andcommitted
[5.3] add $default parameter to query builder when() method (#15428)
* add a $default parameter to the QB when() clause allows you to specify a default in the case that the when() $value is false * add new test for when() method to test $default * remove extra spaces to make StyleCI happy * use the correct index for the bindings in the test * use the full bindings array
1 parent b43cb92 commit 6cf003a

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/Illuminate/Database/Query/Builder.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -459,14 +459,17 @@ public function crossJoin($table, $first = null, $operator = null, $second = nul
459459
*
460460
* @param bool $value
461461
* @param \Closure $callback
462+
* @param \Closure $default
462463
* @return \Illuminate\Database\Query\Builder
463464
*/
464-
public function when($value, $callback)
465+
public function when($value, $callback, $default = null)
465466
{
466467
$builder = $this;
467468

468469
if ($value) {
469470
$builder = call_user_func($callback, $builder);
471+
} elseif ($default) {
472+
$builder = call_user_func($default, $builder);
470473
}
471474

472475
return $builder;

tests/Database/DatabaseQueryBuilderTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,27 @@ public function testWhenCallback()
135135
$this->assertEquals('select * from "users" where "email" = ?', $builder->toSql());
136136
}
137137

138+
public function testWhenCallbackWithDefault()
139+
{
140+
$callback = function ($query) {
141+
return $query->where('id', '=', 1);
142+
};
143+
144+
$default = function ($query) {
145+
return $query->where('id', '=', 2);
146+
};
147+
148+
$builder = $this->getBuilder();
149+
$builder->select('*')->from('users')->when(true, $callback, $default)->where('email', 'foo');
150+
$this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql());
151+
$this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings());
152+
153+
$builder = $this->getBuilder();
154+
$builder->select('*')->from('users')->when(false, $callback, $default)->where('email', 'foo');
155+
$this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql());
156+
$this->assertEquals([0 => 2, 1 => 'foo'], $builder->getBindings());
157+
}
158+
138159
public function testBasicWheres()
139160
{
140161
$builder = $this->getBuilder();

0 commit comments

Comments
 (0)