I have the following input form structure upon submission :
array:6 [▼
"_method" => "PATCH"
"_token" => "h7hb0yLzdYaFY0I4e1I7CQK7Niq9EqgXFTlramn9"
"candidate" => array:4 [▶]
"languages" => array:3 [▼
0 => "ga"
1 => "no"
2 => "sk"
]
"availabilities" => array:2 [▼
"z" => array:1 [▶]
2 => array:3 [▶]
]
"experiences" => array:3 [▶]
]
I am trying to validate the 'availabilities' array keys to make sure they correspond to existing id's in the database:
'availabilities' => 'required|integer|exists:days_of_week,id',
If I use this rule it targets the main array, but the exists
key is passing validation even when I use the browser console to change the id to something like 'z'. It fails on the integer
rule because it retrieves an array as well. How does one validate array keys?
The following example uses a similar form structure. But it does not cover how the employee id could be validated. I saw people add an 'id' key along with 'name' and 'age' for example and to have a rule against that 'id' field, but it is cumbersome.
It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.
To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.
In your request class, override the prepareForValidation() method (which does nothing by default, btw), and explode your comma separated string. Now you can just use Laravel's normal array validation!
If you have control over the input data structure, I suggest to modify it to the following:
[
...,
"availabilities" => [
{
"id": "z",
"data" : [0 => "foo"]
},
{
"id": 2,
"data" : [0 => "bar"]
}
]
]
Then adjust your validation rules, to validate against your database for example
public function rules {
return [
'availabilities' => 'filled',
'availabilities.*.id' => 'required|integer|exists:days_of_week,id',
'availabilities.*.data' => 'required|array'
// etc...
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With