2016-11-15 2 views
0

私はAjax呼び出しに戻す方法を理解しようとしていますが、検証エラーがあった場合、そのページが続くのを防ぎ、それらのエラーをユーザーに表示することができます。 。Laravel検証エラーをAjax呼び出しに戻す

/* 
* Create User After they complete the first part of the form. 
* 
*/ 
public function createUserAndOrder(Request $request) 
{ 
    $validation = $this->validate($request, [ 
     'first_name' => 'required', 
     'last_name' => 'required', 
     'email' => 'required|confirmed|unique:users,email', 
     'email_confirmation' => 'required' 
    ]); 

    $credentials = [ 
     'first_name' => $request->input('first_name'), 
     'last_name' => $request->input('last_name'), 
     'email' => $request->input('email'), 
     'password' => Hash::make(str_random(8)), 
    ]; 

    $user = Sentinel::registerAndActivate($credentials); 

    $user->role()->attach(5); 

    return response()->json([ 
     'success' => true, 
     'errors' => null 
    ]); 
} 

答えて

1

あなたはとしてValidateファサードを使用して、それを試すことができます。

{ 
    'success': false, 
    'errors': { 
     'first_name': [ 
      'The first name field is required.' 
     ], 
     'last_name': [ 
      'The last name field is required.' 
     ] 
    } 
} 
+0

だから、あなたは間違いなく正しいです:これはあなたにこのようなJSONレスポンスを与えるだろう

$validator = \Validator::make($request->all(), [ 'first_name' => 'required', 'last_name' => 'required', 'email' => 'required|confirmed|unique:users,email', 'email_confirmation' => 'required' ]); // Validate the input and return correct response if ($validator->fails()) { return response()->json(array( 'success' => false, 'errors' => $validator->getMessageBag()->toArray() ), 422); } 

。しかし、私はこの結果を得る。 "last_name":[最後の 名前フィールドは必須です] "、" email ":["成功 ":false、"エラー ":{" first_name " "電子メールフィールドが必要です。"]、 "email_confirmation":[" 確認フィールドが必要です"]}} "NetworkError:422 Unprocessable Entity - http://myapp.app/createUserAndOrder"エラーを意味します。 – user3732216

+0

結果はOKです。これをあなたのajax呼び出しで処理する必要があります。 httpステータスコードが422の場合、サーバーから返されたユーザーにエラーを表示できます。 –

+0

ああ、これはajaxコールの成功またはエラーハンドラで行いますか? – user3732216

関連する問題