Skip to content
Advertisement

Laravel, Handling validation errors in the Controller

So i’m working on validating a form’s inputs using the following code:

$request->validate([
    'title' => 'bail|required|max:255',
    'body' => 'required',
]);

So basically, there are two fields in the form, a title and a body and they have the above rules. Now if the validation fails I want to catch the error directly in the controller and before being redirected to the view so that I can send the error message as a response for the Post request. What would be the best way to do it? I understand that errors are pushed to the session but that’s for the view to deal with, but i want to deal with such errors in the controller itself.

Thanks

Advertisement

Answer

If you have a look at the official documentation you will see that you can handle the input validation in different ways.

In your case, the best solution is to create the validator manually so you can set your own logic inside the controller.

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade.

Here a little example:

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'bail|required|max:255',
        'body' => 'required',
    ]);

    // Check validation failure
    if ($validator->fails()) {
       // [...]
    }

    // Check validation success
    if ($validator->passes()) {
       // [...]
    }

    // Retrieve errors message bag
    $errors = $validator->errors();
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement