Search code examples
phplaravellaravel-9laravel-validation

Laravel FormRequest Before Validation


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


Solution

  • 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.

    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;