将验证错误消息格式化为嵌套关联数组

时间:2018-11-08 08:09:41

标签: laravel validation laravel-5.7

我有一个Json数据对象,如下所示

{
  "name": "something",
  "location": {
    "city": "some where",
    "country": "some where",

  }
}

用于验证请求的规则为

[
    'name' => 'required',
    'location.city' => 'required',
    'location.country' => 'required'
]

哪个返回错误消息,如

{
  "name": [
    "The name field is required."
  ],
  "location.city": [
    "The location.city field is required."
  ],
  "location.county": [
    "The location.country field is required."
  ]
}

如何将错误消息格式化为类似于请求的嵌套数组。

{
  "name": [
    "The name field is required."
  ],
  "location": {
    "city": [
      "The city field is required"
    ],
    "country": [
      "The country field is required"
    ]
  }
}

有没有可用的默认方法? 我正在使用Illuminate\Foundation\Http\FormRequest

3 个答案:

答案 0 :(得分:1)

对于您的情况,您需要自己构建错误消息。您仍然可以使用ressources/lang/en/validation邮件文件中的默认邮件。

$validator = Validator::make($request->all(), [
    'name' => 'required',
    'location.city' => 'required',
    'location.country' => 'required'
]);

if ($validator->fails()) {
    return response()->json($yourOwnFormat,422);
    //you can use $validator->errors() to build it
}

答案 1 :(得分:0)

是吗? Laravel Documentation- Customizing the Error Messages

//=require_full_tree ../../../web-app/js

答案 2 :(得分:0)

对于那些寻求解决方案的人来说,这就是我的实现方式

<?php 
namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class UserStoreRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required',
            'location.city' => 'required'
            'location.country' => 'required'
        ];
    }
    public function attributes()
    {
        return [
            'location.city' => 'City'
            'location.country' => 'Country'
        ];
    }
    protected function failedValidation(Validator $validator)
    {
        $errors = $validator->errors()->getMessages();
        $errors_formated = array();
        foreach ($errors as $key => $value) {
        array_set($errors_formated, $key, $value);
        }
        throw new HttpResponseException(response()->json(['error' => $errors_formated], 422));
    }
}

$validator->errors()->getMessages()的结果类似于array_dot()辅助函数的结果。因此,我做了array_dot()的对面,也将属性名称更改为漂亮的名称