/** * 因爲 \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\Controllerlaravel
validateMsg 解決了錯誤信息不會放大異常的message字段的問題,json
validateFilter 則是再進一步的包裝,只返回驗證規則配置的字段,且過濾值爲空字符串的鍵值對ide
參考:
https://learnku.com/docs/laravel/5.7/validation/2262ui