Laravel validate sync input data with intermediate table values always fails

49 views Asked by At

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:

  1. The keys(model ids: 3 and 7) must exist in contestants table.
  2. Each contestant must be the same contestant_type as what the game requires, let's say the game's contestant_type is individual, 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:

  1. The field contestants.3 is invalid.
  2. 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}
    }
}
1

There are 1 answers

0
naamhierzo On

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::exist logic on contestants.*.id.