/**
* 由于 \Laravel\Lumen\Routing\ProvidesConvenienceMethods::validate 在验证不通过时,
* 抛出 \Illuminate\Validation\ValidationException 异常时,message字段用的是固定的 => 'The given data was invalid.'
* 且 \App\Exceptions\Handler::handler 只输出了异常的message字段,
* 故自定义错误信息输出json时无法自定义
*
* 这个方法在 validate 方法基础上修改,在验证不通过时抛出 \App\Exceptions\ValidationException ,
* message为错误堆栈中的第一条信息
*
* demo
* $params = $this->validateFilter($request, [
* 'id' => 'required|string'
* ],[
* 'id.required' => 'id必须传'
* ]);
*
* @param Request $request
* @param array $rules
* @param array $messages
* @param array $customAttributes
* @return array
* @throws ValidationException
*/
public function validateMsg(Request $request, array $rules, array $messages = [], array $customAttributes = [])
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);
if ($validator->fails()) {
throw new ValidationException($validator->errors()->first());
}
return $this->extractInputFromRules($request, $rules);
}
/**
* 调用 \App\Http\Controllers\Lap\BaseController::validateMsg 方法
* 并且只保留在$rules的key中存在的key,且过滤值为空字符串的数据
* @param Request $request
* @param array $rules
* @param array $messages
* @param array $customAttributes
* @return array
* @throws ValidationException
*/
public function validateFilter(Request $request, array $rules, array $messages = [], array $customAttributes = [])
{
$this->validateMsg($request, $rules, $messages, $customAttributes);
// 只保留在$rules的key中存在的key
$rs = collect($request->all())->only(array_keys($rules))->toArray();
// 过滤值为空字符串的数据
return array_filter($rs, function ($item) {
return $item !== "";
});
}
将这两个方法放到 \App\Http\Controllers\Controller 中, 或者自己新建一个BaseController extent \App\Http\Controllers\Controller
validateMsg 解决了错误信息不会放大异常的message字段的问题,
validateFilter 则是再进一步的包装,只返回验证规则配置的字段,且过滤值为空字符串的键值对
参考: https://learnku.com/docs/laravel/5.7/validation/2262 |