Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!