user3732216
user3732216

Reputation: 1589

Laravel Validation of Required With

I'm attempting to set up validation for my request in my controller and I'm trying to figure out how I can have address, city, state, zip all depend on each other as far as if there's a value for one then there must be a value for all of them, address2 is the only one that is stand-alone but depends ONLY on the address. For some reason, this doesn't work. For example, if the city is submitted then validation passes. So I don't quite understand what I"m doing wrong.

'address' => 'required_with_all:city,state,zip|string|nullable',
'address2' => 'required_with:address|string|nullable',
'city' => 'required_with_all:address,state,zip|string|nullable',
'state' => 'required_with_all:address,city,zip|string|size:2|nullable',
'zip' => 'required_with_all:address,city,state|integer|digits:5|nullable'

Upvotes: 4

Views: 14450

Answers (1)

sam
sam

Reputation: 5599

required_with and required_with_all don't work in the way you're interpreting them. required_with_all means this field is required if all of the following fields have values. For example, required_with_all:address,state,zip means "city is required if address and state and zip all have values".

You're trying to achieve:

  • If address has a value, city, state and zip are required
  • If address2 has a value, address is required
  • If city has a value, address, state and zip are required
  • If state has a value, address, city and zip are required
  • If zip has a value, address, city and state are required

The rule you're looking for then is required_with but the logic is different. You can effectively use the required_with rule by anchoring on one field, e.g: anchor against address and your rule in English can be "if address has a value, then city, state and zip are required, or if city, state or zip have a value then address is required" which can be constructed as:

$this->validate($request, [
    'address' => 'required_with:city,state,zip|string|nullable',
    'city' => 'required_with:address|string|nullable',
    'state' => 'required_with:address|string|size:2|nullable',
    'zip' => 'required_with:address|integer|digits:5|nullable'
]);

And for address2 your rule is "address is required if address2 has a value" (which will cascade into causing state, city and zip to be required too). This is again constructed using required_with, we set required_with on address:

$this->validate($request, [
    'address' => 'required_with:city,state,zip,address2|string|nullable',
    'address2' => 'string|nullable',
    'city' => 'required_with:address|string|nullable',
    'state' => 'required_with:address|string|size:2|nullable',
    'zip' => 'required_with:address|integer|digits:5|nullable'
]);

Edit: there was an error in a previous version of this answer, it is now fixed.

Upvotes: 19

Related Questions