@@ -13,6 +13,41 @@ trait Rule
1313{
1414 use ValidationRules;
1515
16+ /**
17+ * Converts validation errors into the response expected by the request type.
18+ *
19+ * @param array<string, mixed> $errors
20+ */
21+ protected function failValidation (array $ errors ): never
22+ {
23+ if (request ()->isAjax () || request ()->isApiRequest ()) {
24+ $ exception = new HttpResponseException (
25+ $ errors ,
26+ Response::HTTP_UNPROCESSABLE_ENTITY
27+ );
28+
29+ $ exception ->setResponse (
30+ (new JsonErrorRenderer ())->render (
31+ $ exception ,
32+ Response::HTTP_UNPROCESSABLE_ENTITY ,
33+ $ errors
34+ )
35+ );
36+
37+ throw $ exception ;
38+ }
39+
40+ $ this ->setErrors ($ errors );
41+ foreach ($ errors as $ key => $ error ) {
42+ session ()->putPeek ($ key , implode (' ' , (array ) $ error ));
43+ }
44+
45+ $ response = redirect ()->back ()->withInput ()->withErrors ($ errors );
46+
47+ throw (new HttpResponseException ($ errors , $ response ->getStatusCode ()))
48+ ->setResponse ($ response );
49+ }
50+
1651 /**
1752 * Validate the input data against the given rules.
1853 *
@@ -50,32 +85,7 @@ public function sanitize(array $rules): array|Response
5085 }
5186
5287 if (!empty ($ errors )) {
53- if (request ()->isAjax () || request ()->isApiRequest ()) {
54- $ exception = new HttpResponseException (
55- $ errors ,
56- Response::HTTP_UNPROCESSABLE_ENTITY
57- );
58-
59- $ exception ->setResponse (
60- (new JsonErrorRenderer ())->render (
61- $ exception ,
62- Response::HTTP_UNPROCESSABLE_ENTITY ,
63- $ errors
64- )
65- );
66-
67- throw $ exception ;
68- }
69-
70- $ this ->setErrors ($ errors );
71- foreach ($ errors as $ key => $ error ) {
72- session ()->putPeek ($ key , implode (' ' , (array )$ error ));
73- }
74-
75- $ response = redirect ()->back ()->withInput ()->withErrors ($ errors );
76-
77- throw (new HttpResponseException ($ errors , $ response ->getStatusCode ()))
78- ->setResponse ($ response );
88+ $ this ->failValidation ($ errors );
7989 }
8090
8191 $ this ->setPassedData ($ input );
0 commit comments