I want to create a Form Request validation and don't know how-to.
I have a form:
<form>
<input type="text" name="fullname[0]">
<input type="text" name="document_num[0]">
<input type="text" name="fullname[1]">
<input type="text" name="document_num[1]">
<input type="text" name="fullname[2]">
<input type="text" name="document_num[2]">
.....
<input type="text" name="fullname[n]">
<input type="text" name="document_num[n]">
<input type="submit">
</form>
table 'users':
id | fullname | document_num
1 | John | 111
2 | Jane | 112
.. | ... | ...
when user clicks submit a request is sent to controller method where it’s first being validated by Form Request (or it can be a regular Validator). So I want to write a rule which checks:
for (i=0; i<numberOfUsersToAdd; i++)
if (‘document_num[$i]’ exists in ‘users’ in field ‘document_num’ ) {
$user = Users::find(id of user in DB having this ‘document_num[$i]’) ;
check if (fullname[$i] == $user->fullname) {
return true} // input-ed users name match his/her name in DB.
else {return false} // input-ed users name doesn't match his/her name in DB.
}
else return true; // document_num[$i] doesn't exists in the database which's ok
if in words: check if any input-ed document_num[$i] exists in the table users, if yes, get the user having this document_nubmer from DB and compare his/her fullname value to fullname[$i] from input.
How to do it?:)
Appreciate any help!:)
Ok. Logic of this validation in
YourFormRequest
is next:document_num
field additionaly as integer. You can add other additional constraints - it dont matter.rules
method ofYourFormRequest
check in loop "is user exists for givendocument_num
?".fullname
. If equals then ok - validation of this field is success. Otherwise if it fails then attach to this field your custom rule that always fails.Let see this approach on a working example.
YourFormRequest.php
CustomValidator.php (place it for example in App\Services folder)
Here you can see two functions. First - to validate rule (we always pass false cause we need it). Second - it just a replacer for error message. You want to know on what field line was this error (for example on third line and fields: fullname[2] and document_num[2] respectively). As i wrote above in comment for attaching fail rule we give the number of row that fails to the validation method (
documentNumFailReplacer
method will replace placeholder :index in error message with the given value)Next step - register this methods in AppServiceProvider.php
And final step - define your custom messages in validation.php