Search code examples
phplaravellaravel-validation

Validating array keys in Laravel


I have the following data coming from a form submission:

[
  "availabilities" => [
    "z" => ["some data"],
    "2" => ["some data"],
  ]
]

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?


Solution

  • 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?