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

Change controller validate helper method to behave like Laravel (#1247) #1248

Merged
merged 8 commits into from
Sep 12, 2022
53 changes: 19 additions & 34 deletions src/Routing/ProvidesConvenienceMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;

Expand Down Expand Up @@ -64,41 +63,27 @@ public function validate(Request $request, array $rules, array $messages = [], a
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);

if ($validator->fails()) {
$this->throwValidationException($request, $validator);
try {
$validated = $validator->validate();

if (method_exists($this, 'extractInputFromRules')) {
// Backwards compatability...
$validated = $this->extractInputFromRules($request, $rules);
}
} catch (ValidationException $exception) {
if (method_exists($this, 'throwValidationException')) {
// Backwards compatability...
$this->throwValidationException($request, $validator);
} else {
$exception->response = $this->buildFailedValidationResponse(
$request, $this->formatValidationErrors($validator)
);

throw $exception;
}
}

return $this->extractInputFromRules($request, $rules);
}

/**
* Get the request input based on the given validation rules.
*
* @param \Illuminate\Http\Request $request
* @param array $rules
* @return array
*/
protected function extractInputFromRules(Request $request, array $rules)
{
return $request->only(collect($rules)->keys()->map(function ($rule) {
return Str::contains($rule, '.') ? explode('.', $rule)[0] : $rule;
})->unique()->toArray());
}

/**
* Throw the failed validation exception.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
protected function throwValidationException(Request $request, $validator)
{
throw new ValidationException($validator, $this->buildFailedValidationResponse(
$request, $this->formatValidationErrors($validator)
));
return $validated;
}

/**
Expand Down