2016-05-04 14 views
2

私はREST JSON APIで検証するためにLaravel 5.2を使用しています。Laravel 5.2 - APIによる検証

私はコントローラを拡張し、ValidatesRequests形質を使用してUserControllerを持っています。

サンプルコード:しかし

public function render($request, Exception $e) 
{ 
    return response()->json([ 
     'responseCode' => 1, 
     'responseTxt' => $e->getMessage(), 
    ], 400); 
} 

responseTxtの検証時には、常に次のとおりです:

Array 
(
    [responseCode] => 1 
    [responseTxt] => The given data failed to pass validation. 
) 

これは私のExceptions/Handler.phpで、私はこのコードを持っているので、例外がスローされます

$this->validate($request, [ 
    'email'   => 'required|email', 
    'password'  => 'required|min:4|max:72', 
    'identifier' => 'required|min:4|max:36', 
    'role'   => 'required|integer|exists:role,id', 
]); 

私は過去にLaravel 4.2を使用しており、検証エラーを覚えています検証に失敗したことの詳細については、

どのフィールドが検証に失敗したのか、その理由を知るにはどうすればよいですか?

答えて

2

Laravel 5.2 validate()メソッドが点灯\検証\にValidationExceptionがスローされますので、あなたが応答が(てgetResponseを使用取得したい場合には)代わりのgetMessage()。

たとえば、この例外を処理するための簡単な方法は、このような何かをやってことができます:

try{ 
    $this->validate($request, [ 
     'email'   => 'required|email', 
     'password'  => 'required|min:4|max:72', 
     'identifier' => 'required|min:4|max:36', 
     'role'   => 'required|integer|exists:role,id' 
    ]); 
}catch(\Illuminate\Validation\ValidationException $e){ 
    return $e->getResponse(); 
} 
2

ValidationExceptionがスローされ、リクエストでJSONが必要な場合は、1つの汎用メッセージとしてレンダリングされます。

代わりのvalidate()メソッドを使用して、手動で、例えば、バリデータを呼び出す:脇として

$validator = Validator::make($request->all(), [ 
    'email'   => 'required|email', 
    'password'  => 'required|min:4|max:72', 
    'identifier' => 'required|min:4|max:36', 
    'role'   => 'required|integer|exists:role,id', 
]); 
if ($validator->fails()) { 
    return new JsonResponse(['errors' => $validator->messages()], 422); 
} 

https://laravel.com/docs/5.2/validation#manually-creating-validators

を、私は422 HTTPステータスコードではなく、400をお勧めします。 400は通常、不正な形式の構文を意味します。検証エラーの原因となるのは、通常、構文が正しいことを意味しますが、データは無効です。 422の手段 "処理不能エンティティ" https://tools.ietf.org/html/rfc4918#section-11.2