1

When I use Validator class in Laravel I am able to catch errors like this for my ajax-

$validator= Validator::make($request->all(),[
            'name' => 'required',
            'email' => 'required|email',
            'age' => 'required|min:3',
            'number' => 'required|numeric',
        ]);
        if($validator->fails()){
            return response()->json([
                'status'=> 400,
                'errors'=>$validator->messages(),
            ]);
        } 

But how can I catch the error messages without using Validator class or using this code-

$request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'age' => 'required|min:3',
            'number' => 'required|numeric',
        ]);

I want to store error messages in a variable in Controller so I can send them to JSON

1
  • catch the exception that is thrown by validate Commented Jul 31, 2022 at 1:28

2 Answers 2

2

https://github.com/laravel/framework/blob/9.x/src/Illuminate/Validation/ValidationException.php

try {
    $request->validate([
        'name' => 'required',
        'email' => 'required|email',
        'age' => 'required|min:3',
        'number' => 'required|numeric',
    ]);
} catch (ValidationException $e) {
    if($request->wantsJson()) {
        return response()->json([
            'status' => 400,
            'errors' => $e->errors(),
        ]);
    }
    
    throw $e; // return to laravel default handler 
}
Sign up to request clarification or add additional context in comments.

Comments

-1

With the $errors var in the blade view Display Errors

2 Comments

I want to store error messages in a variable in Controller so I can send them to JSON.
If your request is in ajax, try to get the 422 status code in fail, this response(422) have the errors in json format

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.