我想要API的自定义验证json响应。现在,默认错误消息是这样的
{"password":["The password must be at least 6 characters."],"type":["The type field is required."]}
我想要
{flag:0,msg:"The password must be at least 6 characters.",data:{"password":["The password must be at least 6 characters."],"type":["The type field is required."]}}
我只希望这种格式适用于我的REST API。我怎样才能实现它。
答案 0 :(得分:2)
我找到了解决方案。
我修改了我的父控制器并添加了formatValidationErrors方法。这是
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
attrs: {
cambiosHtml: 'cambiosHtml',
contenidoHtml: 'contenidoHtml',
pubDate: 'pub_date'
}
});
答案 1 :(得分:1)
验证会触发 HttpResponseException ,我们可以捕捉并采取行动
在控制器操作中执行以下操作
public function abc(Request $request)
{
//using try catch to catch the validation exception thrown
try{
$this->validate($request, $rules);
}catch(\Illuminate\Http\Exception\HttpResponseException $e){
//fetching the error messages
$messages = $e->getResponse()->getSession()->get('errors')->getMessages();
//or you can use $messages = session()->get('errors')->getMessages();
$messages = collect($messages);
$content = [
'flag' => 0,
'data' => $messages->toArray(),
'msg' => $messages->first()[0]
];
return response()->json($content, 400);
}
}