Skip to content

Commit 3118d3f

Browse files
committed
Pass the condition value to "when"
1 parent 5b95f6c commit 3118d3f

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

src/Illuminate/Database/Concerns/BuildsQueries.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,9 @@ public function when($value, $callback, $default = null)
8484
$builder = $this;
8585

8686
if ($value) {
87-
$builder = $callback($builder);
87+
$builder = $callback($builder, $value);
8888
} elseif ($default) {
89-
$builder = $default($builder);
89+
$builder = $default($builder, $value);
9090
}
9191

9292
return $builder;

tests/Database/DatabaseQueryBuilderTest.php

+10-4
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,9 @@ public function testBasicTableWrapping()
132132

133133
public function testWhenCallback()
134134
{
135-
$callback = function ($query) {
135+
$callback = function ($query, $condition) {
136+
$this->assertTrue($condition);
137+
136138
return $query->where('id', '=', 1);
137139
};
138140

@@ -147,16 +149,20 @@ public function testWhenCallback()
147149

148150
public function testWhenCallbackWithDefault()
149151
{
150-
$callback = function ($query) {
152+
$callback = function ($query, $condition) {
153+
$this->assertEquals('truthy');
154+
151155
return $query->where('id', '=', 1);
152156
};
153157

154-
$default = function ($query) {
158+
$default = function ($query, $condition) {
159+
$this->assertFalse($condition);
160+
155161
return $query->where('id', '=', 2);
156162
};
157163

158164
$builder = $this->getBuilder();
159-
$builder->select('*')->from('users')->when(true, $callback, $default)->where('email', 'foo');
165+
$builder->select('*')->from('users')->when('truthy', $callback, $default)->where('email', 'foo');
160166
$this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql());
161167
$this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings());
162168

0 commit comments

Comments
 (0)