skip to Main Content

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


  1. 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:

    public function validate(array $rules, mixed $params)
    {
        if ($this->request->model()->someValue < 100) {
           //throw validation error before the validation of the above rules
        } 
    
        parent::validate($rules, $params);
    }
    

    A potential downside of this approach may be that your custom validation will happen before authorize or prepareForValidation.

    Login or Signup to reply.
  2. 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 flowNO! You don’t have to

    Try this. This will come to function and throw the validation which you desire.

    public function prepareForValidation(): void
    {
        if ($this->request->model()->someValue < 100) {
            throw ValidationException::withMessages([
                'custom_error' => 'Error Message goes here.',
            ]);
        }
    }
    

    As well there is a feature called stopOnFirstFailure

    protected $stopOnFirstFailure = true;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search