laravel validator验证不通过返回The given data was invalid,而不是返回定义的提示信息

misterpan
  • 842
return Validator::make($data, [
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:6'],
            'phone' => ['required', 'string', 'min:8', 'unique:users'],
        ], [
            'email.unique' => '该邮箱已注册',
            'phone.unique' => '该手机号已注册',
        ]);

api请求后

debug
:
{line: 315,…}
class
:
"Illuminate\Validation\ValidationException"
file
:
"/home/vagrant/website/idea/laravel/vendor/laravel/framework/src/Illuminate/Validation/Validator.php"
line
:
315
trace
:
[,…]
message
:
"The given data was invalid."
status_code
:
500

调试的时候去掉验证里的unique就不会有这个异常

回复
阅读 6.9k
5 个回答
2716xzw
  • 2
新手上路,请多包涵

在appExceptionsHandler.php里面的render方法里加入判断

    if ($exception instanceof ValidationException){
            $errors = @$exception->validator->errors()->toArray();
            $message = null;
        if (count($errors)) {
            $firstKey = array_keys($errors)[0];
            $message = $errors[$firstKey][0];
        }
        throw new Exception($message,$exception->getCode());
    }
myprayer
  • 1
新手上路,请多包涵
use IlluminateSupportArr;
if ($exception instanceof ValidationException) {
 return $this->response($code, Arr::first(Arr::collapse($exception->errors())));
}
        if ($validator->fails()) {
            throw new \InvalidArgumentException($validator->messages()->first());
        }

把这个加上试试。

在resources/lang/zh_cn/validation.php中‘attributes’=>[

'email' => '邮箱',
'name' => '姓名',

],试试

你知道吗?

宣传栏