Laravel 表单验证解析

laravel表单验证的异常响应

使用控制器的$this->validate($request,[‘body’ => ‘required’,]);或创建的表单请求验证时,laravel会根据ajax请求或Accept:application/json请求头自动响应Json数据,普通请求会自动重定向之前的页面

源码解析

laravel 异常处理类 HandlerIlluminate\Foundation\Exceptions\Handler

/**
 * Create a response object from the given validation exception.
 *
 * @param \Illuminate\Validation\ValidationException $e
 * @param \Illuminate\Http\Request                   $request
 *
 * @return \Symfony\Component\HttpFoundation\Response
 */
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{

        if ($e->response) {
            return $e->response;
        }

        return $request->expectsJson()
                    ? $this->invalidJson($request, $e)
                    : $this->invalid($request, $e);
}

/**
 * Convert a validation exception into a response.
 *
 * @param \Illuminate\Http\Request                   $request
 * @param \Illuminate\Validation\ValidationException $exception
 *
 * @return \Illuminate\Http\Response
 */
protected function invalid($request, ValidationException $exception)
  {
        $url = $exception->redirectTo ?? url()->previous();

        return redirect($url)
                ->withInput($request->except($this->dontFlash))
                ->withErrors(
                    $exception->errors(),
                    $exception->errorBag
                );
 }

/**
 * Convert a validation exception into a JSON response.
 *
 * @param \Illuminate\Http\Request                   $request
 * @param \Illuminate\Validation\ValidationException $exception
 *
 * @return \Illuminate\Http\JsonResponse
 */
protected function invalidJson($request, ValidationException $exception)
 {
        return response()->json([
            'message' => $exception->getMessage(),
            'errors' => $exception->errors(),
        ], $exception->status);
 }

Trait Illuminate\Http\Concerns\InteractsWithContentTypes

/**
 * Determine if the current request probably expects a JSON response.
 *
 * @return bool
 */
public function expectsJson()
{
     return ($this->ajax() && !$this->pjax()) || $this->wantsJson();
}

/**
 * Determine if the current request is asking for JSON in return.
 *
 * @return bool
 */
public function wantsJson()
{
      $acceptable = $this->getAcceptableContentTypes();

      return isset($acceptable[0]) && Str::contains($acceptable[0], ['/json', '+json']);
}

Handler 类中的convertValidationExceptionToResponse() 方法通过 expectsJson() 判断是否为ajax请求或accept请求头 然后通过invalidJson()将异常响应为json 普通请求,通过invalid()方法响应为重定向