Home > Blockchain >  How to get Laravel FormRequest errors in the controller?
How to get Laravel FormRequest errors in the controller?

Time:07-03

I know i can get the errors in a view with @if ($errors->any()) or similars. But what if I want to get the validation errors in the Controller to return it as JSON?

RegisterRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|string|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'password_confirmation' => 'required|string|min:6|same:password',
        ];
    }
}

AuthController.php register function

public function register(RegisterRequest $request)
{
    $request->errors();
}

Is there a wait to do something like that to get the validation error messages? I couldn't find anything in the documentation

CodePudding user response:

For returning json error response ,you have to override failedValidation in RegisterRequest

  protected function failedValidation(Validator $validator)
    {
       if ($this->ajax()){
        
           throw new HttpResponseException(response()->json($validator->errors(),419));
       } else{
           throw (new ValidationException($validator))
                        ->errorBag($this->errorBag)
                        ->redirectTo($this->getRedirectUrl());
       }
 }

also dont forget to import following

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\ValidationException;

CodePudding user response:

In the Request file

public $validator = null;
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $this->validator = $validator;
}

In the controller function

if (isset($request->validator) && $request->validator->fails()) {
        $request->validator->errors()->messages()
    }

From: How to check if validation fail when using form-request in Laravel?

  • Related