Laravel中的自定义错误消息

时间:2018-03-04 12:25:21

标签: php laravel validation laravel-5 custom-validators

我正在验证Laravel中的数组。我在默认错误消息中得到"0.id has already been taken."。所以我在验证器中添加了第二个参数:'unique' =>':attribute has already been taken. Please fix your data in spreadsheet.'并显示"0.id has already been taken. Please fix your data in spreadsheet."。我添加了第三个参数,它是自定义属性。 ['*.id' =>'Student ID']。但是我想要这样的消息:ID has already been taken. Please fix your data in spreadsheet in line 1.

这是我的完整验证码:



$validate = $request - > validate([
  '*.id' => 'required|unique:students|numeric',
  '*.rfid_number' => 'required|unique:students|numeric',
  '*.first_name' => 'required|alpha|max:100',
  '*.middle_name' => 'alpha|max:100|nullable',
  '*.last_name' => 'required|string|max:100',
  '*.name_extension' => 'alpha|max:10|nullable',
  '*.email' => 'required|email|unique:students',
  '*.photo' => 'string|nullable',
  '*.house_number' => 'required|integer',
  '*.barangay' => 'required|alpha|max:100',
  '*.city' => 'required|alpha|max:100',
  '*.province' => 'required|string|max:100',
  '*.zip_code' => 'required|integer',
  '*.birth_date' => 'required|date|max:100',
  '*.birth_place' => 'string|max:200',
  '*.gender' => 'required|alpha',
  '*.religion' => 'alpha|max:100|nullable',
  '*.landline_number' => 'numeric|max:20|nullable',
  '*.mobile_number' => 'required',
  '*.father_name' => 'string|max:200|required',
  '*.father_occupation' => 'string|max:200|nullable',
  '*.mother_name' => 'string|max:200|required',
  '*.mother_occupation' => 'string|max:200|nullable',
  '*.guardian_name' => 'string|max:200|required',
  '*.guardian_occupation' => 'string|max:200|nullable',
  '*.guardian_address' => 'string|max:200|nullable',
  '*.year' => 'integer|max:10|required',
  '*.section' => 'alpha|max:200|required'
], [
  'unique' => ':attribute has already been taken. Please fix your data in spreadsheet.'
], [ //attributes
  '*.id' => 'Student ID'
]);




1 个答案:

答案 0 :(得分:0)

这样的事情可以解决问题:

$validate = $request->validate([
    //
], [
    //
],
collect($request->all())->keys()->flatMap(function ($index) {
    return ["$index.id" => 'ID'];
})->toArray());

迭代所有索引,最终得到类似的结果:

[
    '0.id' => 'ID',
    '1.id' => 'ID',
    '2.id' => 'ID',
    '3.id' => 'ID',
    '4.id' => 'ID',
    '5.id' => 'ID',
    '6.id' => 'ID',
    '7.id' => 'ID',
]

作为验证器的最终数组