Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation for Array not working

I have the following naming conventions for input fields.

course_details[0][d_Total_Score]
course_details[1][d_Total_Score]
course_details[2][d_Total_Score]

Now I want to validate these fields with some rules. The following is the code I tried.

$validatedData = $request->validate([
    'course_details.0.d_Total_Score' => 'required',
    'course_details.1.d_Total_Score' => 'required',
    'course_details.2.d_Total_Score' => 'required'
]);

I have taken reference from here

But this doesn't seem to be working.

HTML CODE:

<input placeholder="SAT score " class="form-control form-control-sm valid" id="d_Score_Sub_Category_SAT" name="course_details[0][d_Total_Score]" value="" aria-invalid="false" type="text">

RESOLVED: As d3jn said, the validations should not override anywhere.

like image 325
Dushyant Joshi Avatar asked Jul 19 '18 13:07

Dushyant Joshi


1 Answers

You should be able to achieve what you are looking for like this:

course_details.*.d_Total_Score' => 'required'

I recently wrote something similar and I did it like this:

'contacts.*.name' => 'nullable|string|max:255',
'contacts.*.email' => 'nullable|email|max:255',
'contacts.*.phone' => 'nullable|phone:US|max:255',

My HTML looks like this:

<input class="form-control{{ $errors->has('contacts') ? ' is-invalid' : '' }}" id="contacts" name="contacts[0][name]" type="text" value="">
<input class="form-control{{ $errors->has('contacts') ? ' is-invalid' : '' }}" id="contacts" name="contacts[0][email]" type="text" value="">
<input class="form-control{{ $errors->has('contacts') ? ' is-invalid' : '' }}" id="contacts" name="contacts[0][phone]" type="text" value="">

<input class="form-control{{ $errors->has('contacts') ? ' is-invalid' : '' }}" id="contacts" name="contacts[1][name]" type="text" value="">
<input class="form-control{{ $errors->has('contacts') ? ' is-invalid' : '' }}" id="contacts" name="contacts[1][email]" type="text" value="">
<input class="form-control{{ $errors->has('contacts') ? ' is-invalid' : '' }}" id="contacts" name="contacts[2][name]" type="text" value="">

... so on

like image 115
Kevin Pimentel Avatar answered Oct 26 '22 05:10

Kevin Pimentel