Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Add key support to FormRequest validated method #36807

Merged
merged 2 commits into from
Mar 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/Illuminate/Foundation/Http/FormRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
22 changes: 21 additions & 1 deletion tests/Foundation/FoundationFormRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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.
*
Expand Down