我有一个Laravel与FormRequest一起提出的请求,并带有以下规则和消息:
public function rules()
{
return [
'login' => 'required',
'password' => 'required',
];
}
public function messages()
{
return [
'login:required' => 'Login is required',
'password:required' => 'Password is required'
];
}
现在我收到这种答复:
{
"message": "The given data was invalid.",
"errors": {
"login": [
"The login field is required."
],
"password": [
"The password field is required."
]
}
}
但是我想要这样的东西:
{
"status": false,
"validator": true,
"msg": {
"e": {
"login": [
"The login field is required."
],
"password": [
"The password field is required."
]
},
"type": "error"
}
}
这可能吗?
因为现在我使用以下代码来获取此信息:
$item = Validator::make($request->all(), [
'login' => 'required',
'password' => 'required',
]);
if ($item->fails())
return response()->json([
'status' => false,
'validator' => true,
'msg' => [
'e' => $item->messages(),
'type' => 'error'
],
]);
但是我想根据larave的请求(php artisan make:request)来制作
答案 0 :(得分:1)
是的,您可以做到。将此方法添加到您的表单请求类中:
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
// ...
protected function failedValidation(Validator $validator)
{
$data = [
'status' => false,
'validator' => true,
'msg' => [
'e' => $validator->errors(),
'type' => 'error',
],
];
throw new HttpResponseException(response()->json($data, 422));
}