Laravel Validation: required_with_all condition always passing

纵饮孤独 提交于 2019-12-01 22:42:10

I finally figured out the answer. I misunderstood the whole required_if concept. This answer will help anyone who ever gets stuck in here. The key is reading the laravel documentation again and again ;)

Concept

For required_with_all it says: The field under validation must be present only if all of the other specified fields are present.

E.g. param => required_with_all:foo,bar,... means that when foo and bar, both are present, and param is not present, then the validation error will occur.

I misunderstood it such that if param is there, then it requires foo and bar to be there too. Its the other way round though as we just saw.

Alternative

If you need to do a validation as if param is present, foo must be present use the required_with validation rule on foo like so:

'param' => 'required_with:foo',
'foo' => 'required_with: param

This will ensure that if foo or param, anyone of them is present, they will require the other to be present too.

Explanation of my test cases

First test case

'param' => 'required_with_all:foo'

and I passed the following input

array('param' => $param)

The test case failed because foo not being in the input, did not trigger the validation because the rule says only check when foo is present. So instead of passing param as input, simply pass foo as input and you will see the error that param is required when foo is present.

Second test case

'param' => 'required_without_all:foo',

and passing input like so:

array('param' => $param, 'foo' => 'bar')

This validation did not work because it says param is only required when foo is not present. However, in my input I have passed foo. Remove both foo and param and you shall see the error that when foo is not present, param is required.

How silly of me!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!