Skip to content
Advertisement

Validating non-required associative array with required fields

I want to validate that if my request contains a field of associative array type, that array needs to contain specific fields (but only if it’s present)

Ie, array, if present, needs to contain foo:

{ data: {}}

and

{ data: { array: { foo: 1 } }

is fine, but

{ data: { array: {} }

and

{ data: { array: { bar: 1 } }

is not.

I’ve written this validator:

['data.array' => 'sometimes', 'data.array.foo' => 'required']

But it doesn’t accept the first scenario.

>>> IlluminateSupportFacadesValidator::make(
   ['data' => []], 
   ['data.array' => 'sometimes', 'data.array.foo' => 'required']
)->errors()->all();
=> [
     "The data.array.foo field is required.",
   ]

I’d like to avoid using 'data.array.foo' => 'required_with:data.array' (it also doesn’t work for scenario when array is empty)

>>> IlluminateSupportFacadesValidator::make(
   ['data' => ['array' => []]], 
   ['data.array' => 'sometimes', 'data.array.foo' => 'required_with:data.array']
)->errors()->all();
=> []

Are there any non-custom validators that will help me accomplish this?

Advertisement

Answer

You can also use Rule::requiredIf after Laravel 5.6 and up, try this:

$validator =  Validator::make( $request->input(), [
    // ...
    'data.array.foo'=> Rule::requiredIf( function () use ($request){
        return (bool) $request->input('data.array');
    })
]);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement