问题
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