0

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

Sasquatch
  • 87
  • 1
  • 2
  • 7

2 Answers2

2

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;
John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • Hey, thx for the answer, I already found a very simple way, just set the a variable for the validator and access it in the controller. https://stackoverflow.com/questions/48123558/how-to-check-if-validation-fail-when-using-form-request-in-laravel – Sasquatch Jul 02 '22 at 14:24
  • @Sasquatch that would be helpful if you want to access it on the controller.good solution for your scenario – John Lobo Jul 02 '22 at 14:39
0

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?

Sasquatch
  • 87
  • 1
  • 2
  • 7