Class based after validation rules #46757
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 PR proposes improvements to "after" validation rules.
Currently, "after" validation rules must be handled with a callable. I find they generally take the following shape.
It would also be possible to extract this out to a single callable class:
This is well and good, however it doesn't lend itself to rule composition and rule reuse.
If I want to reuse one of these validation checks I end up with clunky to use abstractions.
Or a little bit better, I could use static methods on the extracted classes:
I'd like to propose that introduce a new after rule concept by allowing an array of rules to be passed to the "after" method.
This is based on how normal class based validation rules work. The "after rule" just needs to implement an
after($validator)
method. Callables are also accepted, so you may pass aClosure
or an invokable class.If the class is invokable and has an
after
method, the after method takes precedence.Any state, or services, required by the rule should be passed into the constructor, again matching the way normal class based validation rules work.
Form Requests
As form requests are how a large part of the community handle validation rules, I've made some potential improvements there as well.
In my opinion, adding "after" rules in a form request already feels a little out of place with other Laravel APIs.
I understand that
withValidator
gives you total access to the validator, but in my personal experience I only ever use this method for adding "after" rules to the validator. Additionally, therules
method is called by the container, but thewithValidator
method does not give the same affordance. Dependencies need to be resolved manually.This is where the
after
method comes into play.