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

Format validation error message as nested associative array

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

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

  }
}

用于验证请求的规则是

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

哪个 returns 错误信息像

{
  "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

是吗Laravel Documentation- Customizing the Error Messages

public function messages()
{
    return [
        'location.city' => 'The city field is required',
        'location.county'  => 'The county field is required',
    ];
}

在您的情况下,您需要自己构建错误消息。您仍然可以使用 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
}

对于那些寻找解决方案的人我就是这样实现的

<?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() 的相反操作,还将我的属性名称更改为漂亮的名称