2017-07-06 257 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

太棒了,我沒有意識到這一點。謝謝。我會這樣做,而不是控制器上的驗證方法 –