Laravel 5.5多字段互斥必填验证问题求助
Hey there! I get why your current rules aren't working—let's break this down and fix it.
The Problem with Your Current Rules
Your existing setup uses required_with:field_a and required_if:field_c, together, which creates an unintended "and" requirement instead of the "or" logic you need. Here's the breakdown:
required_with:field_atells Laravel "if field_a is present, field_b must be filled"required_if:field_c,translates to "if field_c is empty, field_b must be filled"
Combined, these two rules force field_b to be filled whenever field_a is true, regardless of field_c's value. The same applies to field_c, which is why both end up being required when field_a is true.
The Fix: Use Closure Validation for "Either/Or" Logic
Laravel 5.5 supports closure-based validation rules, which let you write custom logic exactly for cases like this. Here's how to implement it:
$validationRules = [ 'field_a' => 'boolean', 'field_b' => [ 'string', function ($attribute, $value, $fail) { // Check if field_a is true AND both field_b and field_c are empty if (request()->input('field_a') && empty($value) && empty(request()->input('field_c'))) { $fail('Either field_b or field_c must be provided when field_a is true.'); } } ], 'field_c' => [ 'string', function ($attribute, $value, $fail) { // Same logic for field_c if (request()->input('field_a') && empty($value) && empty(request()->input('field_b'))) { $fail('Either field_b or field_c must be provided when field_a is true.'); } } ], ];
How This Works
- We keep basic type validation (
booleanfor field_a,stringfor the others) to maintain data integrity - The closure checks three conditions at once:
- Is
field_aset totrue? - Is the current field (field_b/field_c) empty?
- Is the other companion field also empty?
- Is
- If all three are true, we trigger a validation error telling the user they need to fill at least one of the two fields.
This way, when field_a is true, users can fill either field_b, field_c, or both—no more forcing both to be required.
Alternative: Create a Reusable Custom Rule (Optional)
If you need this logic in multiple places across your app, you can create a reusable custom rule instead of using closures:
- Generate the rule class via Artisan:
php artisan make:rule RequiredIfEither
- Update the rule's
passesandmessagemethods:
public function passes($attribute, $value) { $fieldA = request()->input('field_a'); $otherField = $attribute === 'field_b' ? 'field_c' : 'field_b'; return !($fieldA && empty($value) && empty(request()->input($otherField))); } public function message() { return 'Either field_b or field_c must be provided when field_a is true.'; }
- Use it in your validation rules:
$validationRules = [ 'field_a' => 'boolean', 'field_b' => ['string', new RequiredIfEither], 'field_c' => ['string', new RequiredIfEither], ];
This keeps your validation code clean and easy to reuse wherever you need this "either/or" conditional check.
内容的提问来源于stack exchange,提问作者Maro Ortega

