Reputation: 735
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?
Upvotes: 1
Views: 1431
Reputation: 5368
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);
Upvotes: 2