Laravel adding custom validation errors

David Carr

Laravel Framework Tutorials PHP & MySQL

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

request()->validate([
    'due_date' => 'required',
    'template' => 'required'
]);

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'
]);

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');
}

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

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

This can be simplified further by instead writing:

$validator->validate();

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

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

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Fathom Analytics $10 discount on your first invoice using this link

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.