Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

274
Vistas
Checking if there is any validation error when using custom form request class

I am using Laravel 5.4. I have a custom form request class where I have my validation rules and messages and I use it in my controller like following :

public function store(CustomFormRequest $request)
{
  //
}

I am using ajax to send the request and when there is any validation error, Laravel throws an error with an HTTP response with a 422 status code including a JSON representation of the validation errors.

But I don't want that. Instead, inside my controller's method, I want to find out if there is any validation error and if there is any then I want to return a response with some additional data along with the validation messages, like this:

// Inside my Controller
public function store(CustomFormRequest $request)
{
   if ($validator->fails())
   {
        $errors = $validator->errors();

        return response()->json(array('status' => 2, 'msg' => $errors->all() ));
    }
}

Could you please help ? Thanks in advance.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

The easiest way to do this would be to override the response() method for the form request class.

To do this you can simply add something like the following to your class:

 import Illuminate\Http\JsonResponse public function response(array $errors) { if ($this->expectsJson()) { return new JsonResponse(['status' => 2, 'msg' => $errors], 422); } return parent::response($errors); }

Don't forget to import Illuminate\Http\JsonResponse

I hope this helps!

about 4 years ago · Santiago Trujillo Denunciar

0

I know you want the logic in your controller, but you can still leverage your request file for this. In the Laravel documentation (assuming you're using the latest version) it's described asAdding Post Bindings to Form Requests :

If you want to add an "after" hook to a form request, you can use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

 /** * Configure the validator instance. * * @param \Illuminate\Validation\Validator $validator * @return void */ public function withValidator($validator) { $validator->after(function ($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add('field', 'Something is wrong with this field!'); } }); }
about 4 years ago · Santiago Trujillo Denunciar

0

try this:

form.ajaxSubmit({
    async: false,
    type: yourMethod,
    url: yourRoute,
    headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
    dataType: 'json',
    success: function(data){
        location.href = data.redirect_to;
    },
    error: function(data) {
        var errors = data.responseJSON;
        var errorsArr = [];
        for (error in errors) {
            errorsArr.push(errors[error]);
        }

        errorsArr = $.map(errorsArr, function(n){
            return n;
        });

        alert("<strong class='text-danger'>" + errorsArr.join("<br>") + "</strong>");
        console.log(errors);

    }
});

and in your controller store method make return:

return response()->json(['redirect_to' => '/your_route']);
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda