Laravel 5 change request form failed validation

I have a form request to validate my credentials. The application is a mobile API, and I would like this class to return formatted JSON in case of failed validation, and not what it does by default (redirection).

I tried to override the failedValidation method from Illuminate\Foundation\Http\FormRequest . but this does not seem to work. Any ideas?

code:

 <?php namespace App\Http\Requests; use App\Http\Requests\Request; use Illuminate\Contracts\Validation\Validator; class RegisterFormRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return TRUE; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email' => 'email|required|unique:users', 'password' => 'required|min:6', ]; } } 
+6
source share
4 answers

Looking at the following function in Illuminate\Foundation\Http\FormRequest , it seems that Laravel handles it correctly.

  /** * Get the proper failed validation response for the request. * * @param array $errors * @return \Symfony\Component\HttpFoundation\Response */ public function response(array $errors) { if ($this->ajax() || $this->wantsJson()) { return new JsonResponse($errors, 422); } return $this->redirector->to($this->getRedirectUrl()) ->withInput($this->except($this->dontFlash)) ->withErrors($errors, $this->errorBag); } 

And according to the wantsJson function in Illuminate\Http\Request below, you should explicitly look for the JSON answer,

  /** * Determine if the current request is asking for JSON in return. * * @return bool */ public function wantsJson() { $acceptable = $this->getAcceptableContentTypes(); return isset($acceptable[0]) && $acceptable[0] == 'application/json'; } 
+1
source

There is no need to redefine any function. just add

 Accept: application/json 

In the header of the form. Laravel will return the response in the same URL and in JSON format.

+4
source

This is my decision, and it works well at my end. I added the function below the request code:

 public function response(array $errors) { if ($this->ajax() || $this->wantsJson()) { return Response::json($errors); } return $this->redirector->to($this->getRedirectUrl()) ->withInput($this->except($this->dontFlash)) ->withErrors($errors, $this->errorBag); } 

The response function is well handled by laravel. It will automatically return if you request json or ajax.

0
source

Just add the following function to your query:

 use Response; public function response(array $errors) { return Response::json($errors); } 
0
source

Source: https://habr.com/ru/post/988145/


All Articles