api使用Request这种方式验证数据,如果失败就会返回422错误
use ApiResponse;
protected $routeName = null;
public function __construct ()
{
// 这里我使用了获取到了路由别名
$this->routeName = request()->route()->getName();
}
public function authorize()
{
//开启校验
return true;
}
public function rules()
{
//我这里使用的是别名,并没有一个方法写一个Request
switch ($this->routeName){
case 'api.auth.weChat':
return [
'pid'=>'required',
'access_token'=>'required',
];
break;
}
}
public function messages ()
{
//同上
switch ($this->routeName){
case 'api.auth.weChat':
return [
'pid.required'=>'required',
'access_token.required'=>'required',
];
break;
}
}
protected function failedValidation(Validator $validator)
{
//获得错误
$errors = $validator->errors()->toArray();
//如果有错误就获取到所有错误
if($errors) $errors = $this->getAllErrors($errors);
//抛出一个HttpResponseException异常,apiParametersMissing是我封装的response()->json()方法而已
throw new HttpResponseException($this->apiParametersMissing('参数错误',$errors));
}
注意这里的Validate是use Illuminate\Contracts\Validation\Validator; 否则会报类找不到
public function getAllErrors (array $errors)
{
$response = [];
foreach ($errors as $key => $error) {
$response[ $key ] = $error[0];
}
return $response;
}
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson()) {
// 捕获错误消息.并且返回
return $this->getJsonErrMesByRes($errors);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
最后我们就如愿的拿到了非Http错误的返回数据