1

I need to add custom tag in response if the validation fails in FormRequest.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreMessage extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:100',
            'email' => 'required|email',
            'message' => 'required|max:1000'
        ];
    }

    public function withValidator(\Illuminate\Validation\Validator $validator)
    {
        $validator->after(function ($validator) {

               if($validator->fails()) {
                   $validator->errors()->add('status', 'error');
               }

        });
    }

}

If my any of the validation fails only then I need to add status = error in json response else I need to add status = success.

Also my response status is nested under errors tag I need it to be at level 0.

    {
  "message": "The given data was invalid.",
  "errors": {
    "name": [
      "The name may not be greater than 100 characters."
    ],
    "status": [
      "error"
    ]
  }
}

Purpose of this is I am sending Ajax request to submit a form i need a flag to identify whether error occurred or not. Is there any better way to do this. Pardon me if I am asking silly question. I am newbie to laravel. Any help would be appreciated.

1 Answer 1

2

From the docs (search for "AJAX"):

When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

In your Javascript, you can catch this happening in a .fail() handler.

UPDATE Simple example, doesn't handle formatting multiple validation errors but gives you the idea:

$.ajax( ... )
.fail(function(xhr, status, error) {
    if (error === 'Unprocessable Entity') {
        // validation failure
        var msg = '';    
        for (error in xhr.responseJSON) {
            msg += xhr.responseJSON[error];
        };
        alert(msg);
    }
});
Sign up to request clarification or add additional context in comments.

7 Comments

’t panic thanks mate that helped. On query is it safe to match Unprocessable Entity in if block. Will it always return this or is there is any safest method.
@Abhishek Good question. I think it is safe, it is the textual portion of the HTTP status (quoted from jQuery docs), so it will always match exactly response code 422. That's what Laravel validation failure returns, and AFAIK it won't return it in any other circumstances.
this is what I call a perfect response of doubt with proper explanation
@Abhishek if you are using > 5.2 laravel than use axios instead of ajax call. Axios is more powerful library to work with.
@Abhishek Axios is a different library and independent one. You can use it without using Vue.js. No need to migrate from jQuery to Vuejs, it requires lots of efforts and too much work. I am just suggesting you to use axios instead of jquery.ajax method.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.