[英]Adding an Error Title and Message to JSON in PHP (Laravel)
$rules = ['email' => 'required', 'password' => 'required'];
$message = ['email.required' => 'Email cannot be empty', 'password.required' => 'Password cannot be empty'];
$v = Validator::make($request->all(), $rules, $message);
$error = $v->messages();
if ($v->fails()) {
return response()->json(["code" => "400", "error" => ["code" => "10", "title"=>"" ,"message" => $error->first()
]]);
}
The code above would return an error block in my JSON 上面的代码将在我的JSON中返回一个错误块
error : {
code: 11
message: "Some error message"
}
However I would add a title field like below. 但是我会在下面添加一个标题字段。
error : {
code: 11
title: "Some error title"
message: "Some error message"
}
How should I do this validation? 我该怎么做这个验证? I need the
.required
我需要
.required
Can anyone please explain a little bit please? 有人可以请一点解释一下吗?
if you want this kind of validation error message format, I think you should build something a little bit more "complex" of what actually you have out of the box. 如果你想要这种验证错误信息格式,我认为你应该构建一些更复杂的“开箱即用”的东西。
Here's what you get with a simple validation test. 这是您通过简单的验证测试得到的。
This is the code I used. 这是我使用的代码。
Route::get('/', function () {
$data = ['name' => ''];
$rules = ['name' => 'required'];
$v = \Validator::make($data, $rules);
dd($v->errors());
});
... and that's the output. ......这就是输出。
MessageBag {#145 ▼
#messages: array:1 [▼
"name" => array:1 [▼
0 => "The name field is required."
]
]
#format: ":message"
}
"Ok, so what I could do?" “好的,我能做什么?”
First of all, some assumptions. 首先,一些假设。 I see that you're taking only the first error.
我看到你只拍了第一个错误。 So, you would get something like this:
所以,你会得到这样的东西:
"The name field is required."
Working this way, you lose the "name" information. 以这种方式工作,您将丢失“名称”信息。 All you have is a simple string message.
你所拥有的只是一个简单的字符串消息。 Not a big deal, considering what you want to achieve.
考虑到你想要达到的目标,没什么大不了的。
So, I would work different. 所以,我会工作不同。 There are many ways to do what I'm going to do, I will just show you a procedure.
有很多方法可以做我将要做的事情,我只会告诉你一个程序。
First of all, let's take the first element of the array. 首先,让我们来看一下数组的第一个元素。
$errors = $v->errors();
$firstElement = reset($errors);
dd($firstElement);
I will get something like this: 我会得到这样的东西:
array:1 [▼
"name" => array:1 [▼
0 => "The name field is required."
]
]
Now, starting from this you could do something like 现在,从这开始你可以做类似的事情
$key = key($firstElement);
$value = reset($firstElement)[0];
To get the key and the value . 获得关键和价值 。
Finally, you should use them to build your response. 最后,您应该使用它们来构建您的响应。
Here's an example: 这是一个例子:
return response()->json(
[
"code" => "400",
"error" =>
[
"code" => "10",
"title"=> "Field $key is empty." ,
"message" => $value
]
]);
Obviously I suggest you to create a class to implement the entire mechanism, in order to isolate responsibilities. 显然,我建议你创建一个类来实现整个机制,以便隔离职责。
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.