8000 [9.x] Add key support to FormRequest validated method (#36807) · laravel/framework@8b40e8b · GitHub
[go: up one dir, main page]

Skip to content

Commit 8b40e8b

Browse files
[9.x] Add key support to FormRequest validated method (#36807)
* Add key option to $request->validated() Co-authored-by: mattstauffer <matt@tighten.co> * Make FoundationFormRequestTest method names consistent Co-authored-by: mattstauffer <matt@tighten.co>
1 parent 6daecf4 commit 8b40e8b

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

src/Illuminate/Foundation/Http/FormRequest.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,10 +188,18 @@ protected function failedAuthorization()
188188
/**
189189
* Get the validated data from the request.
190190
*
191-
* @return array
191+
* @param string|null $key
192+
* @param string|array|null $default
193+
* @return mixed
192194
*/
193-
public function validated()
195+
public function validated($key = null, $default = null)
194196
{
197+
if (! is_null($key)) {
198+
return data_get(
199+
$this->validator->validated(), $key, $default
200+
);
201+
}
202+
195203
return $this->validator->validated();
196204
}
197205

tests/Foundation/FoundationFormRequestTest.php

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ public function testPrepareForValidationRunsBeforeValidation()
106106
$this->createRequest([], FoundationTestFormRequestHooks::class)->validateResolved();
107107
}
108108

109-
public function test_after_validation_runs_after_validation()
109+
public function testAfterValidationRunsAfterValidation()
110110
{
111111
$request = $this->createRequest([], FoundationTestFormRequestHooks::class);
112112

@@ -115,6 +115,26 @@ public function test_after_validation_runs_after_validation()
115115
$this->assertEquals(['name' => 'Adam'], $request->all());
116116
}
117117

118+
public function testValidatedMethodReturnsOnlyRequestedValidatedData()
119+
{
120+
$request = $this->createRequest(['name' => 'specified', 'with' => 'extras']);
121+
122+
$request->validateResolved();
123+
124+
$this->assertEquals('specified', $request->validated('name'));
125+
}
126+
127+
public function testValidatedMethodReturnsOnlyRequestedNestedValidatedData()
128+
{
129+
$payload = ['nested' => ['foo' => 'bar', 'baz' => ''], 'array' => [1, 2]];
130+
131+
$request = $this->createRequest($payload, FoundationTestFormRequestNestedStub::class);
132+
133+
$request->validateResolved();
134+
135+
$this->assertEquals('bar', $request->validated('nested.foo'));
136+
}
137+
118138
/**
119139
* Catch the given exception thrown from the executor, and return it.
120140
*

0 commit comments

Comments
 (0)
0