skip to Main Content

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


  1. You can use the Rule in Laravel

    php artisan make:rule
    

    by creating a custom rule you are free to write any kind of validation that you want.

    Login or Signup to reply.
  2. You have to use sometimes in validation

    $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' => ['sometimes', 'required_if:shape,rounded', 'numeric', 'gt:0'],
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search