1

I am using...

$validator  = Validator::make(...) 

...to validate my input. However, instead of using that method, for API purposes, I would like to make use of Laravel's Validation Exception class.

Currently, I am trying:

// Model (Not Eloquent Model)
Validator::make(...) 

// Controller
try { $model->createUser(Request $request); }
catch(ValidationException $ex)
{
    return response()->json(['errors'=>$ex->errors()], 422);
}

However, the validation in the model does not appear to throw any validation exceptions. I can still get the errors by using $validator->errors(). Yet, that is still defeating my purpose.

I am trying to keep really clean controllers with only try and catch statements; therefore, keeping any and all logic and out of controllers.

How can I utilize the ValidationException to do just that?

1 Answer 1

2

I do not know what happens in your $model->createUser(Request $request);, but if you use the Validator facade then you'd have to process the validation yourself as in:

use Validator;

...

$validator = Validator::make($input, $rules);

if ($validator->fails()) {
    // With a "Accept: application/json" header, this will format the errors
    // for you as the JSON response you have right now in your catch statement
    $this->throwValidationException($request, $validator);
}

On the other hand you might want to use the validate() method in your controller as it does all of the above for you:

$this->validate($request, $rules);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I was unaware of that. Thanks. I will do that instead, the validate method on the controller

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.