2017-07-06 107 views
0

我使用...Laravel利用ValidationException

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

...来验证我的输入。但是,为了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来做到这一点?

回答

1

,我不知道你$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); 
+0

太棒了,我没有意识到这一点。谢谢。我会这样做,而不是控制器上的验证方法 –