I'm trying to sync with additional data, like this:
$game->contestants()->sync([3 => ['budget' => 30.5], 7 => ['budget' => 25]])
Which works as expected, but I am trying to validate this input with the following rule:
- The keys(model ids: 3 and 7) must exist in
contestantstable. - Each contestant must be the same
contestant_typeas what thegamerequires, let's say the game'scontestant_typeisindividual, then the contestant should also be an individual.
So what I did was (I am using Form Request validation btw):
$rules['contestants.*'] = [
Rule::exists('contestants', 'id')->where('contestant_type', $this->game->contestant_type),
];
But no matter how valid the contestant is, validation error always says:
- The field contestants.3 is invalid.
- The field contestants.7 is invalid.
But when I remove the where condition, validation succeeds, but I guess it's wrong, because when I try to input non existing contestant id, it still succeeds.
Any idea why is this? or where I went wrong?
Btw, this is how the request data looks in postman:
{
"contestants": {
"3": {"budget": 30.5},
"7": {"budget": 25}
}
}
What your current code is doing is checking if contestants has an ID of "contestants.3" and "contestants.7".
You should extract the ID to the array and then validate that using your
Rule::existlogic oncontestants.*.id.