我正在构建一个json REST API。我需要扩展验证库"error":"validation_failed"
,为所有验证失败的 json 输出添加静态标签。
// create the validation rules ------------------------
$rules = array(
'firstName' => 'required',
'lastName' => 'required',
'email' => 'required|email|unique:users',
'reg_type' => 'required|in:'.implode(",", $this->types),
'oauthUId' => 'required_if:reg_type,'.implode(",", $this->externalTypes),
'password' => 'required_if:reg_type,email',
'parentId' => 'sometimes|integer|exists:user_accounts,id',
);
// do the validation ----------------------------------
$validator = Validator::make(Input::all(), $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// get the error messages from the validator
return $validator->messages();
}
else {
// validation successful ---------------------------
}
我检查了 laravel/validator.php 并发现它应该被添加到 Illuminate\Support\MessageBag 对象。
$this->messages->add($attribute, $message);
如何通过扩展验证器类来做到这一点。
我需要这样的输出json
{
"error":
"validation_failed",
"firstName":
"The first name field is required.",
"lastName":
"The last name field is required.",
"reg_type":
"The selected reg type is invalid."
}