DEV Community

Cover image for Laravel adding custom validation errors
David Carr
David Carr

Posted on • Updated on • Originally published at dcbblog.dev

Laravel adding custom validation errors

Validating in Laravel can be really simple for instance take this example:

request()->validate([
    'due_date' => 'required',
    'template' => 'required'
]);
Enter fullscreen mode Exit fullscreen mode

This will validate that data in the request object and passes an array of rules which will validate both due_date and template exist and are set in the request object. If the validation fails then a redirect is automatically executed to the previous page passing both the user input and an array of errors.

For simple validation, this is amazing! simple and effective but in cases when you need to add a custom error message to the error object this cannot be used instead use the Validator class and pass in the request object and an array of rules.

$validator = Validator::make(request()->all(), [
    'due_date' => 'required',
    'template' => 'required'
]);
Enter fullscreen mode Exit fullscreen mode

To add a custom error with this approach an errors->add() method can be called:

if (request('event') == null) {
    $validator->errors()->add('event', 'Please select an event');
}
Enter fullscreen mode Exit fullscreen mode

The add method accepts two params the custom name and its value.

Now at this point, nothing would happen as the validation has not been run to complete this you would normally write:

if ($validator->fails()) {
    return redirect('post/create')
                ->withErrors($validator)
                ->withInput();
}
Enter fullscreen mode Exit fullscreen mode

Calling ->fails() executes the validation and will redirect with input and errors upon failure.

This can be simplified further by instead writing:

$validator->validate();
Enter fullscreen mode Exit fullscreen mode

Which does the same thing but automatically.

Putting it all together:

//setup Validator and passing request data and rules
$validator = \Validator::make(request()->all(), [
    'due_date' => 'required',
    'template' => 'required'
]);

//hook to add additional rules by calling the ->after method
$validator->after(function ($validator) {

    if (request('event') == null) {
        //add custom error to the Validator
        $validator->errors()->add('event', 'Please select an event');
    }

});

//run validation which will redirect on failure
$validator->validate();
Enter fullscreen mode Exit fullscreen mode

Now for cases where custom errors are required to be added this allows this without too much extra work.

Top comments (1)

Collapse
 
luisenricke profile image
Luis Villalobos

Thanks dude, you save me a lot of time