我在用..。
$validator = Validator::make(...) ...to验证我的输入。但是,出于API的目的,我想使用Laravel的Validation Exception类,而不是使用该方法。
目前,我正在尝试:
// Model (Not Eloquent Model)
Validator::make(...)
// Controller
try { $model->createUser(Request $request); }
catch(ValidationException $ex)
{
return response()->json(['errors'=>$ex->errors()], 422);
}但是,模型中的验证似乎不会引发任何验证异常。我仍然可以通过使用$validator->errors()获得错误。然而,这仍然违背了我的目的。
我试图通过只使用try和catch语句来保持控制器的整洁;因此,将所有的逻辑和控制器排除在外。
我如何利用ValidationException来做到这一点呢?
发布于 2017-07-07 02:23:48
我不知道您的$model->createUser(Request $request);中发生了什么,但是如果您使用Validator外观,那么您必须自己处理验证,如下所示:
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);
}另一方面,您可能希望在控制器中使用validate()方法,因为它为您完成了上述所有操作:
$this->validate($request, $rules);https://stackoverflow.com/questions/44946516
复制相似问题