skip to Main Content

I have a Laravel rule for validation which is like this:-

 $ruleCondition  = array(
     'home_address'          => 'required_if:delivery,y',
     'office_address'        => 'required_if:delivery,y',
     'farm_house_address'    => 'required_if:delivery,y',
 );

If delivery is y, then home_address, office_address and farm_house_address are required.

However, I want to modify this a bit. If delivery is y, then either one of the home_address, office_address or farm_house_address would be required.

How can I do this?

2

Answers


  1. You can use sometimes like this

    $validator = Validator::make($data, [
        'delivery' => 'required', # Assumt this is your delivery
        'home_address' => 'sometimes|required',
        'office_address' => 'sometimes|required',
        'farm_house_address' => 'sometimes|required',
    ]);
    
    # Custom validation
    
    $validator->sometimes(['home_address', 'office_address', 'farm_house_address'], function ($input) {
        return !empty($input->home_address) || !empty($input->office_address) || !empty($input->farm_house_address);
    }, 'required_if:delivery,y');
    

    after if logic to $validator->fails() handle fail

    Not sure $input->home_address or $input['home_address']. Please check

    Login or Signup to reply.
  2. You can add additional validators that require each without the otheres:

     $ruleCondition  = array(
         'home_address'          => 'required_if:delivery,y|required_without:office_address,farm_house_address',
         'office_address'        => 'required_if:delivery,y|required_without:home_address,farm_house_address',
         'farm_house_address'    => 'required_if:delivery,y|required_without:home_address,office_address',
     );
    

    (note: I’ve not tested this but it should work)

    Ref: https://laravel.com/docs/10.x/validation#rule-required-without

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search