Create the response for when a request fails validation.

@param  Request  $request
@param  array|string  $errors
@return JsonResponse|Response
507952
protected function buildFailedValidationResponse(Request $request, $errors)
    {
        $content = [
            'error'             => "The submitted data did not pass validation.",
            'validation_errors' => (array) $errors
        ];

        return ($request->ajax() && !$request->pjax() || $request->wantsJson())
            ? new JsonResponse($content, 422)
            : new Response($content, 422);
    }
275766
private function makeNotFoundResponse(Request $request): Promise {
        return $this->errorHandler->handleError(Status::NOT_FOUND, null, $request);
    }
164058
protected function createInstance(JsonApiRequest $request, ErrorCollection $errors)
    {
        // for Roles allowed to define ID on creation that's why we don't use default (parent) method

        $instance = $this->getModel()->newInstance();

        $instance->setAttribute($instance->getKeyName(), $request->getId());

        return $instance;
    }
1043785
protected function sendFailedLoginResponse( Request $request )
	{
		return Redirect::back()->withInput( $request->only( $this->loginUsername(), 'remember' ) )->withErrors( [
				$this->loginUsername() => $this->getFailedLoginMessage(),
			] );
	}
169800
public function callback(Request $request)
    {
        if ($request->has('error')) {
            switch ($request->get('error')) {
                case 'access_denied':
                    abort(401);
                    break;
                case 'temporarily_unavailable':
                    abort(503);
                    break;
                case 'invalid_request':
                case 'unauthorized_client':
                case 'unsupported_response_type':
                case 'invalid_scope':
                case 'server_error':
                default:
                    abort($request->server->get('REDIRECT_STATUS', 500));
                    break;
            }
        }

        $code = $request->get('code');
        $http = new Client();

        try {
            $response = $http->post(config('openid.server') . '/oauth/token', [
                'form_params' => [
                    'grant_type'    => 'authorization_code',
                    'client_id'     => config('openid.client.id'),
                    'client_secret' => config('openid.client.secret'),
                    'redirect_uri'  => route('openid.callback'),
                    'code'          => $code,
                ],
            ]);

            $this->checkError($response);
            $response = json_decode($response->getBody());

            session([
                'openid_token'  => $response->id_token,
                'access_token'  => $response->access_token,
                'refresh_token' => $response->refresh_token,
                'expires_at'    => Carbon::now()->addSeconds($response->expires_in),
            ]);
        } catch (\Exception $exception) {
            if ($exception instanceof ServerException || $exception instanceof ClientException) {
                $this->checkError($exception->getResponse());
            }

            abort($exception->getCode() !== 0 ? $exception->getCode() : 500);
        }

        return redirect()->intended();
    }
121250
public function validate(Request $request, array $rules = [], array $filters = [])
    {
        $all = $request->all();

        return $request->getValidation()->make($all, $rules, $filters);
    }
1125711
protected function resolveDynamicFormRequestErrors(Request $request)
	{
		try {
			$config = app('itemconfig');
			$fieldFactory = app('admin_field_factory');
		} catch (\ReflectionException $e) {
			return null;
		}
		if (array_key_exists('form_request', $config->getOptions())) {
			try {
				$model = $config->getFilledDataModel($request, $fieldFactory->getEditFields(), $request->id);

				$request->merge($model->toArray());
				$formRequestClass = $config->getOption('form_request');
				app($formRequestClass);
			} catch (HttpResponseException $e) {
				//Parses the exceptions thrown by Illuminate\Foundation\Http\FormRequest
				$errorMessages = $e->getResponse()->getContent();
				$errorsArray = json_decode($errorMessages);
				if (!$errorsArray && is_string ( $errorMessages )) {
					return $errorMessages;
				}
				if ($errorsArray) {
					return implode(".", array_dot($errorsArray));
				}
			}
		}
		return null;
	}
993151
public function failureAction(Request $request)
    {
        $orderId = $request
            ->query
            ->get('id', false);

        $failureRoute = $this
            ->redirectionRoutes
            ->getRedirectionRoute('failure');

        $redirectUrl = $this
            ->urlGenerator
            ->generate(
                $failureRoute->getRoute(),
                $failureRoute->getRouteAttributes(
                    $orderId
                )
            );

        return new RedirectResponse($redirectUrl);
    }
1169006
public function render($request)
    {
        $contents = [
            'error' => 'access_denied',
            'message' => $this->message,
        ];

        if ($this->hint) {
            $contents['hint'] = $this->hint;
        }

        // Return a properly formatted error according
        // to RFC 6749, Section 5.2. <goo.gl/EeUqjz>
        return new JsonResponse($contents, 401, [
            'WWW-Authenticate' => 'Bearer realm="OAuth"',
        ]);
    }
1255460
public static function validate($form, $errors, $message = '', $style = null) {
		$args = $errors;

		return new JsonView([
			'code'    => self::ERROR,
			'target'  => $form,
			'message' => $message,
			'style'   => $style,
			'args'    => $args,
			'action'  => self::ACT_VALIDATE
		], ['ajax' => '1'], 422);
	}
195091
public function uploadImageAction(Request $request): Response
    {
        if ($this->isValidCsrfToken($request)) {
            $data = new ImageAssetUploadData(
                $request->files->get(self::FILE_KEY),
                $request->request->get(self::LANGUAGE_CODE_KEY)
            );

            $errors = $this->validator->validate($data);
            if ($errors->count() === 0) {
                try {
                    $file = $data->getFile();

                    $content = $this->imageAssetMapper->createAsset(
                        $file->getClientOriginalName(),
                        new ImageValue([
                            'path' => $file->getRealPath(),
                            'fileSize' => $file->getSize(),
                            'fileName' => $file->getClientOriginalName(),
                            'alternativeText' => null,
                        ]),
                        $data->getLanguageCode()
                    );

                    return new JsonResponse([
                        'destinationContent' => [
                            'id' => $content->contentInfo->id,
                            'name' => $content->getName(),
                            'locationId' => $content->contentInfo->mainLocationId,
                        ],
                        'value' => $this->imageAssetMapper->getAssetValue($content),
                    ]);
                } catch (Exception $e) {
                    return $this->createGenericErrorResponse($e->getMessage());
                }
            } else {
                return $this->createInvalidInputResponse($errors);
            }
        }

        return $this->createInvalidCsrfResponse();
    }
151013
private function resolveErrorHandlerFromAcceptHeader(Request $request): callable
    {
        // Try to find an error handler for one of the accepted content types
        $accepts = $request->hasHeader('Accept') ? $request->getHeaderLine('Accept') : $this->defaultContentType;
        /** @var array $accepts */
        $accepts = explode(',', $accepts);
        foreach ($accepts as $accept) {
            if (! $this->errorHandlerManager->has($accept)) {
                continue;
            }

            return $this->errorHandlerManager->get($accept);
        }

        // If it wasn't possible to find an error handler for accepted content type, use default one if registered
        if ($this->errorHandlerManager->has($this->defaultContentType)) {
            return $this->errorHandlerManager->get($this->defaultContentType);
        }

        // It wasn't possible to find an error handler
        throw new InvalidArgumentException(sprintf(
            'It wasn\'t possible to find an error handler for ["%s"] content types. '
            . 'Make sure you have registered at least the default "%s" content type',
            implode('", "', $accepts),
            $this->defaultContentType
        ));
    }
329725
protected function handleValidation($request, BaseException $e)
    {
        if (!is_a($e, ValidationFail::class)) {
            return;
        }

        // Log validation errors so Reporter will output them
        // if (Config::get('app.debug')) Log::debug(print_r($e->validation->messages(), true));

        // Respond
        if ($request->ajax()) {
            return response()->json($e->validation->messages(), 400);
        }

        return back()->withInput()->withErrors($e->validation);
    }
112984
public function onLogoutSuccess(Request $request)
    {
        $jsonPolicy = new JsonResponsePolicy();

        if ($jsonPolicy->isAcceptable($request)) {
            return new JsonResponse([
                'error' => 0,
                'url' => $this->targetUrl,
            ]);
        } else {
            return $this->httpUtils->createRedirectResponse($request, $this->targetUrl);
        }
    }
727064
public function error($errors = false)
    {
        if ($errors === false) {
            return $this->error;
        } else {
            if (is_array($errors) === true) {
                foreach ($erros as $error) {
                    $this->error($error);
                }
            }
        }
        $this->error[] =(string) $errors;
    }
180355
public function response(array $errors)
    {
        $messages = implode(' ', array_flatten($errors));

        return Response::json(ResponseUtil::makeError($messages), 400);
    }
640336
private function createInvalidInputResponse(ConstraintViolationListInterface $errors): JsonResponse
    {
        $errorMessages = [];
        foreach ($errors as $error) {
            $errorMessages[] = $error->getMessage();
        }

        return $this->createGenericErrorResponse(implode(', ', $errorMessages));
    }