我正在试图找出如何传回我的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
]);
}
答案 0 :(得分:1)
您可以使用Validate
Facade作为:
$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);
}
这会给你一个像这样的JSON响应:
{
'success': false,
'errors': {
'first_name': [
'The first name field is required.'
],
'last_name': [
'The last name field is required.'
]
}
}