Laravel, Handling validation errors in the Controller
Asked Answered
C

2

5

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

Cree answered 17/12, 2019 at 10:25 Comment(2)
for this the best way to use custom validations of laravel where you can define your own error messageVilmavim
The solution shared in above comment is correct , You would have to use this class to make that code work use Illuminate\Support\Facades\Validator;Nomadic
O
10

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();
}
Oakley answered 17/12, 2019 at 10:54 Comment(0)
T
2

For someone who wants to know how to get validation errors after page redirection in the controller:

$errors = session()->get('errors');
if ($errors) {

    //Check and get the first error of the field "title"
    if ($errors->has('title')) {
         $titleError = $errors->first('title');
    }

    //Check and get the first error of the field "body"
    if ($errors->has('body')) {
         $bodyError = $errors->first('body');
    }
}

$errors will contain an instance of Illuminate/Contracts/Support/MessageBag

You can read more on the API here: https://laravel.com/api/8.x/Illuminate/Contracts/Support/MessageBag.html

Note: I have tested it in Laravel 8, it should work on Laravel 6+ if you get the MessageBag from the session

Tolan answered 16/9, 2022 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.