Laravel中的自定义错误消息

问题描述 投票:0回答:1

我正在验证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'
]);
php laravel validation laravel-5 custom-validators
1个回答
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',
]

作为验证器的最终数组

© www.soinside.com 2019 - 2024. All rights reserved.