我正在使用laravel开发REST服务。我想从laravel表单验证中获取确切的错误消息 控制器
$validator = Validator::make(array('email' => Input::get('email')), array('email' => array('required', 'email')));
if ($validator->fails()) {
$this->res_err_data['error'] = $validator->messages();
return Response::json($this->res_err_data, 400);
}
错误消息
{
"status": "2",
"data": [],
"error": {
"email": [
"The email field is required."
]
}
}
我想收到"The email field is required."
而不是["The email field is required."]
答案 0 :(得分:0)
试试这个......
Add following line after email field
{{ $errors->first('email', '<div class="errorsetting">:message</div>') }}
Add following line after "$validator = Validator::make(array('email' => Input::get('email')), array('email' => array('required', 'email')));"
if ($validator->fails()) {
return Redirect::to('toyourpage')->withInput()->withErrors($validation->messages());
}
答案 1 :(得分:0)
您可以使用array_map()
来更改结构:
$meessages = $validator->messages();
$this->res_err_data['error'] = array_map(function($errors){
return isset($errors[0]) ? $errors[0] : null;
}, $messages);
答案 2 :(得分:0)
像这样在您的代码中使用此$validator->errors()->first()
$validator = Validator::make(array('email' => Input::get('email')), array('email' => array('required', 'email')));
if ($validator->fails()) {
$this->res_err_data['error'] = $validator->errors()->first();
return Response::json($this->res_err_data, 400);
}