Validating Array Keys in Laravel 5.2

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...
    ];
}

@Jurriën Dokter 's answer is a work around and uses PHP functions not Laravel rules, It works but if you really want to benefit from Laravel validation rules you have to tweak the validation request a little bit. Here's how:
Make a custom request:

php artisan make:request NameOfRequest  

Place the following function in the request:

protected function prepareForValidation()
{
    $this->merge([
        'availabilities_ids' => array_keys($this->get('availabilities'))
    ]);
}

In the rules:

    public function rules()
    {
        return [
            // place your other rules here .. 
            'availabilities'       => 'required|array|min:1',
            'availabilities.*'     => 'array',
            'availabilities_ids'      => 'exists:App\Models\Availability,id'
        ];
    }

This way you get the benefit of using Laravel's native validation rules through modifying the request params before validation.
See this link to know more about prepareForValidation https://laravel.com/docs/8.x/validation#prepare-input-for-validation


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?

Tags:

Laravel 5.2