【问题标题】:Custom error message in LaravelLaravel 中的自定义错误消息
【发布时间】:2018-08-12 05:12:44
【问题描述】:

我在 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'
]);

【问题讨论】:

  • 请出示您的验证码
  • 我已经更新了。你能帮我吗
  • 您想将ID 替换为1、2 还是3?或者只是ID
  • 我想要输出类似“学生证已被占用。请在 X 行的电子表格中修复您的数据。”其中 X 应该是默认错误消息中 0.id 中的数字
  • @ClydeDexterSantiago 你能回复吗?

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


【解决方案1】:

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

$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',
]

作为验证器的最终数组

【讨论】:

    猜你喜欢
    • 2015-12-22
    • 2020-12-05
    • 2020-02-26
    • 2017-08-17
    • 2019-10-28
    • 2017-05-30
    • 2016-04-17
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多