[英]How to convert Laravel 7 error json to this new json
您好,我想知道是否可以将 Laravel 的错误 json 转换为这个新的 json。 我正在使用 Laravel 7
{
"message": "The given data was invalid.",
"errors": {
"email": [
"email is already in use"
],
"username": [
"username is already in use"
]
}
}
至
{
"message": "The given data was invalid.",
"errors": {
"email": "email is already in use",
"username": "username is already in use"
}
}
在您的 controller 内部,如果您使用 Validator 外观验证您的 POST 请求,您可以将错误转换为一个集合和 map。
use Illuminate\Support\Facades\Validator;
// Faking the Request array & Commenting out to fail request
$input = [
// 'username' => 'username',
// 'password' => 'password',
];
$validator = Validator::make((array) $input, [
'username' => 'required|unique|string',
'password' => 'required|string',
]);
if ($validator->fails()) {
$formatted = collect($validator->errors())->map(function ($error) {
return $error[0];
});
return response()->json([
'message' => 'The given data was invalid.',
'errors' => $formatted,
], 422);
}
我会提出一种不同的方法来解决这个问题。
在您的用户 model 中,您可以添加一个名为ValidationBook
的 class 方法。
public static function ValidationBook($except = [], $append = [])
{
$book = ['rules' => [], 'messages' => []];
$book['rules'] = [
'user.email' => 'required|email|unique:users,email',
'user.password' => 'required|min:8',
'user.password_confirmation' => 'required|min:8|same:user.password',
];
$book['messages'] = [
'user.email.required' => 'The email is required',
'user.email.email' => 'The email must be a valid email address.',
'user.email.unique' => 'This email is already in use.',
'user.password.required' => 'A password is required.',
'user.password.min' => 'Password musst have at least 8 characters',
'user.password_confirmation.required' => 'The password confirmation is required.',
'user.password_confirmation.same' => 'Passwords doesn't match',
];
if (!empty($except)) {
$except = array_flip($except);
$book['rules'] = array_diff_key($book['rules'], $except);
}
if (!empty($append))
$book = array_merge_recursive($book, $append);
return $book;
}
然后,在收到请求的 controller 中,您可以简单地执行以下操作:
$vb = User::ValidationBook();
$vb["rules"]["user.client_secret"] .= $request->input("user")["client_id"];
$data = $request->validate($vb["rules"], $vb["messages"]);
请注意,您可以定义每个错误,如果有多个问题,响应将发送所有失败的规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.