How to customize JSON format of error in validation in Lumen(Laravel)

二次信任 提交于 2021-02-08 06:54:19

问题


I am sending error messages like this in case of errors in getting data from DB or any other issue:

return response()->json(['status' => 'Failed' ,'state'=>'100' , 'message'=>'You have not registered yet.' ], 401);

This gives me a JSON which has everything defined so I easily show the message whatever the problem is.

But in case of error in case of validation, I don't seem to have the power to change the format of the error response JSON.

   $this->validate($request, [
    'email' => 'required',
    'password' => 'required'
    ]);

I want to customize the error format as the one given above so that I don't have to change my error showing mechanism.


回答1:


You can manually create a validator and add your custom response if it fails, like this:

$validator = Validator::make($request->all(), [
    'email' => 'required',
    'password' => 'required'
]);

if ($validator->fails()) {
    return response()->json(['status' => 'Failed' ,'state'=>'100' , 'message'=> $validator->errors()->first() ], 401);
}


来源:https://stackoverflow.com/questions/46857342/how-to-customize-json-format-of-error-in-validation-in-lumenlaravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!