60 lines
1.5 KiB
PHP
60 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Abstracts;
|
|
|
|
use Illuminate\Foundation\Http\FormRequest;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Contracts\Validation\Validator;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
abstract class CustomFormRequest extends FormRequest
|
|
{
|
|
function __construct()
|
|
{
|
|
parent::__construct();
|
|
}
|
|
|
|
/**
|
|
* Handle a failed validation attempt.
|
|
*
|
|
* @param \Illuminate\Contracts\Validation\Validator $validator
|
|
* @return void
|
|
*
|
|
* @throws \Illuminate\Validation\ValidationException
|
|
*/
|
|
protected function failedValidation(Validator $validator)
|
|
{
|
|
|
|
throw new ValidationException($validator, $this->response(
|
|
$this->formatErrors($validator)
|
|
));
|
|
}
|
|
|
|
/**
|
|
* Format the errors from the given Validator instance.
|
|
*
|
|
* @param \Illuminate\Contracts\Validation\Validator $validator
|
|
* @return array
|
|
*/
|
|
protected function formatErrors(Validator $validator)
|
|
{
|
|
return $validator->getMessageBag()->toArray();
|
|
}
|
|
|
|
/**
|
|
* Get the proper failed validation response for the request.
|
|
*
|
|
* @param array $errors
|
|
* @return \Symfony\Component\HttpFoundation\Response
|
|
*/
|
|
public function response(array $errors)
|
|
{
|
|
if ($this->expectsJson()) {
|
|
return new JsonResponse($errors, 422);
|
|
}
|
|
|
|
return $this->redirector->to($this->getRedirectUrl())
|
|
->withInput($this->except($this->dontFlash))
|
|
->withErrors($errors, $this->errorBag);
|
|
}
|
|
} |