Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

275
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda