How to add extra data in response if Validation fails in FormRequest Laravel

空扰寡人 提交于 2021-01-28 09:28:52

问题


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:


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);
    }
});


来源:https://stackoverflow.com/questions/46410162/how-to-add-extra-data-in-response-if-validation-fails-in-formrequest-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!