'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?



Solution 1:[1]

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();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan