Skip to content

Commit 6914aa6

Browse files
committed
fix(http): refine FormRequest JSON failure detection
- Return default JSON validation errors for JSON bodies or explicit JSON Accept headers - Stop treating XHR/AJAX requests as JSON automatically - Document the behavior and update FormRequest tests Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent aad4c9d commit 6914aa6

4 files changed

Lines changed: 83 additions & 12 deletions

File tree

‎system/HTTP/FormRequest.php‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,19 +149,29 @@ protected function prepareForValidation(array $data): array
149149
* The default implementation redirects back with input and flashes validation
150150
* errors via the standard ``_ci_validation_errors`` channel (the same channel
151151
* used by controller-level validation and readable by ``validation_errors()``
152-
* helpers). For JSON/AJAX requests it returns a 422 JSON response instead.
152+
* helpers). For JSON requests or requests that prefer JSON responses, it
153+
* returns a 422 JSON response instead.
153154
*
154155
* @param array<string, string> $errors
155156
*/
156157
protected function failedValidation(array $errors): ResponseInterface
157158
{
158-
if ($this->request->is('json') || $this->request->isAJAX()) {
159+
if ($this->shouldReturnJsonResponse()) {
159160
return service('response')->setStatusCode(422)->setJSON(['errors' => $errors]);
160161
}
161162

162163
return redirect()->back()->withInput();
163164
}
164165

166+
/**
167+
* Determine whether the default validation failure response should be JSON.
168+
*/
169+
private function shouldReturnJsonResponse(): bool
170+
{
171+
return $this->request->is('json')
172+
|| $this->request->negotiate('media', ['text/html', 'application/json'], true) === 'application/json';
173+
}
174+
165175
/**
166176
* Called when the isAuthorized() check returns false. Override to customize.
167177
*/

‎tests/system/HTTP/FormRequestTest.php‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -346,8 +346,35 @@ public function testResolveRequestReturns422ForJsonRequest(): void
346346
$this->assertSame(422, $response->getStatusCode());
347347
}
348348

349-
public function testResolveRequestReturns422ForAjaxRequest(): void
349+
public function testResolveRequestReturns422WhenJsonIsPreferred(): void
350350
{
351+
service('superglobals')->setServer('HTTP_ACCEPT', 'application/json');
352+
$formRequest = $this->makeFormRequest($this->makeRequest());
353+
354+
$response = $formRequest->resolveRequest();
355+
356+
$this->assertInstanceOf(ResponseInterface::class, $response);
357+
$this->assertSame(422, $response->getStatusCode());
358+
359+
$body = json_decode($response->getBody(), true);
360+
$this->assertArrayHasKey('errors', $body);
361+
$this->assertArrayHasKey('title', $body['errors']);
362+
}
363+
364+
public function testResolveRequestRedirectsForAjaxRequest(): void
365+
{
366+
service('superglobals')->setServer('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
367+
$formRequest = $this->makeFormRequest($this->makeRequest());
368+
369+
$response = $formRequest->resolveRequest();
370+
371+
$this->assertInstanceOf(ResponseInterface::class, $response);
372+
$this->assertSame(303, $response->getStatusCode());
373+
}
374+
375+
public function testResolveRequestReturns422ForAjaxRequestThatPrefersJson(): void
376+
{
377+
service('superglobals')->setServer('HTTP_ACCEPT', 'application/json');
351378
service('superglobals')->setServer('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
352379
$formRequest = $this->makeFormRequest($this->makeRequest());
353380

@@ -357,6 +384,17 @@ public function testResolveRequestReturns422ForAjaxRequest(): void
357384
$this->assertSame(422, $response->getStatusCode());
358385
}
359386

387+
public function testResolveRequestRedirectsForWildcardAcceptHeader(): void
388+
{
389+
service('superglobals')->setServer('HTTP_ACCEPT', '*/*');
390+
$formRequest = $this->makeFormRequest($this->makeRequest());
391+
392+
$response = $formRequest->resolveRequest();
393+
394+
$this->assertInstanceOf(ResponseInterface::class, $response);
395+
$this->assertSame(303, $response->getStatusCode());
396+
}
397+
360398
// -------------------------------------------------------------------------
361399
// Authorization failure
362400
// -------------------------------------------------------------------------
@@ -678,7 +716,7 @@ public function testInvalidFormRequestRedirectsWebRequest(): void
678716
}
679717

680718
// -------------------------------------------------------------------------
681-
// Integration: validation failure - JSON / AJAX
719+
// Integration: validation failure - JSON
682720
// -------------------------------------------------------------------------
683721

684722
#[RunInSeparateProcess]
@@ -697,13 +735,28 @@ public function testInvalidFormRequestReturns422ForJsonRequest(): void
697735
}
698736

699737
#[RunInSeparateProcess]
700-
public function testInvalidFormRequestReturns422ForAjaxRequest(): void
738+
public function testInvalidFormRequestReturns422WhenJsonIsPreferred(): void
701739
{
702-
service('superglobals')->setServer('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
740+
service('superglobals')->setServer('HTTP_ACCEPT', 'application/json');
703741

704742
$response = $this->runRequest('/posts', 'store', 'POST');
705743

706744
$this->assertSame(422, $response->getStatusCode());
745+
746+
$body = json_decode((string) $response->getBody(), true);
747+
$this->assertArrayHasKey('errors', $body);
748+
$this->assertArrayHasKey('title', $body['errors']);
749+
}
750+
751+
#[RunInSeparateProcess]
752+
public function testInvalidFormRequestRedirectsForAjaxRequest(): void
753+
{
754+
service('superglobals')->setServer('HTTP_REFERER', 'http://example.com/posts/create');
755+
service('superglobals')->setServer('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
756+
757+
$response = $this->runRequest('/posts', 'store', 'POST');
758+
759+
$this->assertSame(303, $response->getStatusCode());
707760
}
708761

709762
// -------------------------------------------------------------------------

‎user_guide_src/source/incoming/form_requests.rst‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ Type-hint the FormRequest class as a parameter of your controller method. The
4040
framework instantiates it, runs authorization and validation, and passes the
4141
resolved object to your method. If validation fails, the default behavior
4242
redirects back with errors for web requests or returns a 422 JSON response for
43-
JSON/AJAX requests - the method body is never reached.
43+
JSON request bodies or requests that prefer ``application/json`` - the method
44+
body is never reached.
4445

4546
.. literalinclude:: form_requests/002.php
4647
:lines: 2-
@@ -209,10 +210,14 @@ control of what happens when a request is rejected. Both methods return a
209210
.. literalinclude:: form_requests/008.php
210211
:lines: 2-
211212

212-
The default ``failedValidation()`` already detects JSON and AJAX requests and
213-
returns the appropriate 422 response automatically. Override it only when you
214-
need a different behavior, such as always responding with JSON even for ordinary
215-
browser requests.
213+
The default ``failedValidation()`` returns a 422 JSON response for JSON request
214+
bodies or requests that prefer ``application/json`` through the ``Accept``
215+
header. Otherwise, it redirects back with input and validation errors.
216+
217+
.. note:: The ``X-Requested-With: XMLHttpRequest`` header alone does not select
218+
a JSON response. If an AJAX client expects JSON validation errors, send an
219+
``Accept: application/json`` header. If your application needs HTML
220+
fragments for AJAX form failures, override ``failedValidation()``.
216221

217222
.. _form-request-flash-normalized:
218223

‎user_guide_src/source/incoming/form_requests/013.php‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ protected function prepareForValidation(array $data): array
2525
// Override so that old() reflects the normalized values on redirect.
2626
protected function failedValidation(array $errors): ResponseInterface
2727
{
28-
if ($this->request->is('json') || $this->request->isAJAX()) {
28+
if (
29+
$this->request->is('json')
30+
|| $this->request->negotiate('media', ['text/html', 'application/json'], true) === 'application/json'
31+
) {
2932
return service('response')->setStatusCode(422)->setJSON(['errors' => $errors]);
3033
}
3134

0 commit comments

Comments
 (0)