是否有办法将laravel默认错误消息操作或更改为JSON响应。我正在构建一个API。我得到的当前回应是
{
"email": [
"The email has already been taken."
],
"phone": [
"The phone has already been taken."
]
}
我希望它像这样
{
"errors": [
{
"field": "username",
"message": "The username field is required."
},
{
"field": "password",
"message": "The password field is required."
}
]
}
$validator = Validator::make($request->all(), [
'email' => 'required|string|email|max:50|unique:customers',
'phone' => 'required|string|max:10|min:10|unique:customers',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->messages(), 200);
}
答案 0 :(得分:2)
从messageBag中提取错误并根据需要对其进行格式化:
const {username, description, reviews} = this.props
<p>{ reviews || 'No reviews' }</p>
<p>{ username ? formatName(username) : "" }</p>
<p>{ description && 'Has description!' }</p>
答案 1 :(得分:0)
如果您在给出第一个示例时得到了对象,则可以通过for..in
循环来更改它
var response = {
"email": [
"The email has already been taken."
],
"phone": [
"The phone has already been taken."
]
};
var allError = [];
for(let i in response){
allError.push({
field: i,
message: response[i][0]
});
}
var errors = {errors:allError};
console.log(errors);
&#13;
你不应该从php / laravel更改,因为那样你就无法为单个输入显示多个错误。
也永远不会更改也适用于网络的基本代码。您不能只考虑API,它也可以用于网络。