Here’s my code:
$rules = [
'shape' => ['required', 'in:cubic,rounded'],
'height' => ['required', 'numeric', 'gt:0'],
'length' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
'width' => ['required_if:shape,cubic', 'numeric', 'gt:0'],
'diameter' => ['required_if:shape,rounded', 'numeric', 'gt:0'],
]
My need is when shape is cubic, validation will ignore diameter (even it gives a value 0).
For example: if I post shape=cubic&height=10&length=10&width=10&diameter=0
, it will returns The diameter field must be greater than 0
.
For diameter field, I want the rules ['numeric', 'gt:0']
only available when shape is rounded, otherwise there should be no rules like []
.
I try to use required_if
but it’s not suit for this case.
Laravel has no rule named if
, only required_if
or other ..._if
rules.
2
Answers
You can use the Rule in Laravel
by creating a custom rule you are free to write any kind of validation that you want.
You have to use
sometimes
in validation