diff --git a/src/Illuminate/Http/Concerns/InteractsWithInput.php b/src/Illuminate/Http/Concerns/InteractsWithInput.php index 69b00672de88..d5c58e8a3f38 100644 --- a/src/Illuminate/Http/Concerns/InteractsWithInput.php +++ b/src/Illuminate/Http/Concerns/InteractsWithInput.php @@ -112,14 +112,19 @@ public function hasAny($keys) * * @param string $key * @param callable $callback + * @param callable|null $default * @return $this|mixed */ - public function whenHas($key, callable $callback) + public function whenHas($key, callable $callback, callable $default = null) { if ($this->has($key)) { return $callback(data_get($this->all(), $key)) ?: $this; } + if ($default) { + return $default(); + } + return $this; } @@ -185,14 +190,19 @@ public function anyFilled($keys) * * @param string $key * @param callable $callback + * @param callable|null $default * @return $this|mixed */ - public function whenFilled($key, callable $callback) + public function whenFilled($key, callable $callback, callable $default = null) { if ($this->filled($key)) { return $callback(data_get($this->all(), $key)) ?: $this; } + if ($default) { + return $default(); + } + return $this; } diff --git a/tests/Http/HttpRequestTest.php b/tests/Http/HttpRequestTest.php index c019499419f6..33611a32d28a 100644 --- a/tests/Http/HttpRequestTest.php +++ b/tests/Http/HttpRequestTest.php @@ -304,7 +304,7 @@ public function testWhenHasMethod() { $request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => '', 'city' => null]); - $name = $age = $city = $foo = false; + $name = $age = $city = $foo = $bar = false; $request->whenHas('name', function ($value) use (&$name) { $name = $value; @@ -322,17 +322,24 @@ public function testWhenHasMethod() $foo = 'test'; }); + $request->whenHas('bar', function () use (&$bar) { + $bar = 'test'; + }, function () use (&$bar) { + $bar = true; + }); + $this->assertSame('Taylor', $name); $this->assertSame('', $age); $this->assertNull($city); $this->assertFalse($foo); + $this->assertTrue($bar); } public function testWhenFilledMethod() { $request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => '', 'city' => null]); - $name = $age = $city = $foo = false; + $name = $age = $city = $foo = $bar = false; $request->whenFilled('name', function ($value) use (&$name) { $name = $value; @@ -350,10 +357,17 @@ public function testWhenFilledMethod() $foo = 'test'; }); + $request->whenFilled('bar', function () use (&$bar) { + $bar = 'test'; + }, function () use (&$bar) { + $bar = true; + }); + $this->assertSame('Taylor', $name); $this->assertFalse($age); $this->assertFalse($city); $this->assertFalse($foo); + $this->assertTrue($bar); } public function testMissingMethod()