diff --git a/src/Illuminate/Foundation/Http/FormRequest.php b/src/Illuminate/Foundation/Http/FormRequest.php index 8c2da9699600..e82bf967bb2b 100644 --- a/src/Illuminate/Foundation/Http/FormRequest.php +++ b/src/Illuminate/Foundation/Http/FormRequest.php @@ -188,10 +188,18 @@ protected function failedAuthorization() /** * Get the validated data from the request. * - * @return array + * @param string|null $key + * @param string|array|null $default + * @return mixed */ - public function validated() + public function validated($key = null, $default = null) { + if (! is_null($key)) { + return data_get( + $this->validator->validated(), $key, $default + ); + } + return $this->validator->validated(); } diff --git a/tests/Foundation/FoundationFormRequestTest.php b/tests/Foundation/FoundationFormRequestTest.php index d394566ce6cb..1d68e487235e 100644 --- a/tests/Foundation/FoundationFormRequestTest.php +++ b/tests/Foundation/FoundationFormRequestTest.php @@ -106,7 +106,7 @@ public function testPrepareForValidationRunsBeforeValidation() $this->createRequest([], FoundationTestFormRequestHooks::class)->validateResolved(); } - public function test_after_validation_runs_after_validation() + public function testAfterValidationRunsAfterValidation() { $request = $this->createRequest([], FoundationTestFormRequestHooks::class); @@ -115,6 +115,26 @@ public function test_after_validation_runs_after_validation() $this->assertEquals(['name' => 'Adam'], $request->all()); } + public function testValidatedMethodReturnsOnlyRequestedValidatedData() + { + $request = $this->createRequest(['name' => 'specified', 'with' => 'extras']); + + $request->validateResolved(); + + $this->assertEquals('specified', $request->validated('name')); + } + + public function testValidatedMethodReturnsOnlyRequestedNestedValidatedData() + { + $payload = ['nested' => ['foo' => 'bar', 'baz' => ''], 'array' => [1, 2]]; + + $request = $this->createRequest($payload, FoundationTestFormRequestNestedStub::class); + + $request->validateResolved(); + + $this->assertEquals('bar', $request->validated('nested.foo')); + } + /** * Catch the given exception thrown from the executor, and return it. *