[12.x] Introduce Rule::oneOf() for Validating Against Multiple Rule Sets (#54880) #54946
+336
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Note
Non-Breaking Change
This PR does not modify any existing validation rules—it only introduces a new rule.
This PR introduces a new validation rule,
Rule::oneOf()
, allowing a field to be validated against multiple predefined rule sets, ensuring that at least one set fully passes. This feature is particularly useful for validating tagged unions, discriminator-based validation (as seen in OpenAPI specs), or alternative input structures in FormRequest validation.Some keypoints on how this would benefit end users:
required_if
,sometimes
, or custom logic,oneOf()
provides an expressive way to define alternative validation paths using objects which don't need to be necessarily flat maps of validation rules.A practical example is the one I've mentioned in my discussion, with some additional attempts to implement this as a custom rule as well.
A sort of "emergent behavior" from this implementation is also the possibility of nested validations using nested
OneOf
rules as well, which would allow for deep parsing of body parameters inFormRequests
I look forward to receiving feedback and fixing, implementing or improving the implementation in the event that the current one is not deemed worthy.
Example Usage
Regular rule declaration (Base case for oneOf)
The
p1
value effectively determines what the "shape" of the object to be validated should beRegular rule declaration using dynamic sets from OpenAPI Spec [Discussion Example]
Nested rules (Which becomes emergent from the nature of the
passes()
method inOneOf
validation)