0
votes

I am validating an array in Laravel. I get "0.id has already been taken." in default error message. So I added a 2nd parameter in my validator: 'unique' =>':attribute has already been taken. Please fix your data in spreadsheet.' and shows "0.id has already been taken. Please fix your data in spreadsheet.". I added the 3rd parameter which is the custom attribute. ['*.id' =>'Student ID']. But I want to have a message like this: ID has already been taken. Please fix your data in spreadsheet in line 1.

Here's my full validation code:

$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
please show your validation code - Sohel0415
I updated it already. Can you help me - Clyde Dexter Santiago
Do you want to replace ID by 1, 2 or 3? Or just it will be ID ? - Niklesh Raut
I want to have an output like "Student ID has already been taken. Please fix your data in spreadsheet in line X." where X should be the number in 0.id in default error message - Clyde Dexter Santiago
@ClydeDexterSantiago can you respond? - Jonathan

1 Answers

0
votes

Something like this would do the trick:

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

Iterate over all the indexes so you end up with something like:

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

As your final array to the validator