I have an API that sends an array of staff, some are existing objects that need to be updated and some are new objects that need to be created, they all need to be validated and as part of that is testing for a unique email. I am using a FormRequest:
$rules = [
'staff.*.name' => 'required|max:128',
'staff.*.email' => 'required|email|unique:users',
'staff.*.description' => 'max:512',
];
So the problem is, as I am sure you can see, the email address fails unique validation on update. This is because the mechanism for ignoring the email if the ID is the same as the item being validated is causing me an issue.
I can not see a way of getting the ID of the object currently being validated so I can access its ID. So I can't add the part:
'staff.*.email' => 'required|email|unique:users,email,id,' . $currentStaff->id
I can't see much about this specific issue so I am assuming I am barking up the wrong tree doing it this way or missing something insanely obvious.
The payload below:
{
"staff": [
{
"name":"Libbie Turcotte",
"email":"[email protected]",
"updated_at":"2019-12-05 19:28:59",
"created_at":"2019-12-05 19:28:59",
"id":53
},
{
"name":"Person Dave",
"email":"[email protected]",
},
{
"name":"Staff Name",
"email":"[email protected]",
}
]
}
IDsomewhere in thestaff[]array of input, either asstaff[id]orstaff[][id]. And the rules will need to be constructed based on the input, so you can loop it and reference:foreach($request->input('staff') AS $staff){ ... // use $staff['id'] }, orforeach($request->input('staff') AS $id => $staff){ ... // use $id }. If you can show your form/ajax request that is sendingstaffinput, that would help.1and2have a different unique rule than3, due to the inclusion/omission ofid.