I was looking for a way to validate some logic before the formRequest validation but i couldn’t find anything. Does it have some similar hook like after()
within the withValidator
method or maybe the constructor?
MyController:
class MyController extends Controller {
public function myMethod(MyFormRequest $request) {
//the request is validate before executing anything here
}
}
MyFormRequest:
class MyFormRequest extends FormRequest
{
protected $stopOnFirstFailure = true;
public function rules(): array
{
return [
'name' => 'integer',
//etc
];
}
public function withValidator(Validator $validator): void
{
if ($this->request->model()->someValue < 100) {
//throw validation error before the validation of the above rules
}
}
}
I can’t put the validation in the normal rules
set because i don’t have that attribute in the request data, that specific validation is on a model on the request something tied to the session(like a user model) that i need to check first before anything else but i also can’t put it in the authorization
method or middleware because is not an auth check.
I can always add it in the prepareForValidation
but then i’d have an attribute in the validatedData that i don’t need further in the flow…
2
Answers
Suggestion 1: As you’re not validating the form inputs, consider moving this part of validation elsewhere. Middleware may be a good candidate.
Suggestion 2: If you want this logic to be in one place, try overriding one of the following methods (not sure which one you need):
validate
,validateWithBag
,validateResolved
. You will do something like this:A potential downside of this approach may be that your custom validation will happen before
authorize
orprepareForValidation
.I can always add it in the prepareForValidation but then i’d have an attribute in the validatedData that i don’t need further in the flow – NO! You don’t have to
Try this. This will come to function and throw the validation which you desire.
As well there is a feature called
stopOnFirstFailure