Validating Array Keys in Laravel 5.2

Patrick.SE

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.

Jurriën Dokter

You can do this by adding a custom validator. See also: https://laravel.com/docs/5.2/validation#custom-validation-rules.

For example:

\Validator::extend('integer_keys', function($attribute, $value, $parameters, $validator) {
    return is_array($value) && count(array_filter(array_keys($value), 'is_string')) === 0;
});

You can then check the input with:

'availabilities' => 'required|array|integer_keys',

Found the array check here: How to check if PHP array is associative or sequential?

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related