[8.x] Introduce Conditional trait on validation rules #37504
Merged
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.
This introduces a new
Conditional
trait that adds the commonly-used->when()
and->unless()
helpers. I've limited this PR to adding these helpers to validation rules, although there's an opportunity to remove some duplication on the query builder, mailables, etc., if you want to expand the scope.I find myself using
when()
more and more often, and usually miss it on objects that don't have it. One classic use case is in a FormRequest object:Something like this lets me re-use the same ruleset for create and update operations. If I'm updating an existing page, I ignore that model from the unique rule. If I'm creating a new page, there's nothing to ignore.
This can be used to add stricter options to a password rule if the logged in user has privileged access, or dynamically changing image dimension requirements based on some dynamic input.