Laravel Validate ->validate() method removed custom added errors?

I'm trying to use the Laravel validator to include some custom error messages before I run the validate() method. However it appears that running this method then removed any previously added errors.

I can confirm that the error message appears when I dump out the validator messages before hitting validate()

    $validator = Validator::make(
        $this->data,
        $this->rules
    );

    $validator->errors()->add('meal', 'The meal field is required.');

    $validator->validate();

How I can validate my data but still include the error relating to the meal?

1 answer

  • answered 2022-05-04 14:36 Jonathan

    I believe what you want to use is the after validation hook. This will allow you to add more errors like so:

    $validator = Validator::make(
        $this->data, 
        $this->rules
    );
    
    $validator->after(function ($validator) {
        $validator->errors()->add(
            'field', 'Something is wrong with this field!'
        );
    });
     
    $validator->validate();
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum