In this article I compile a few tricks that you won’t read the official documentation. Here are some small tricks on how you could handle requests differently.
#1 Change rules depending on the method
You can avoid a lot of code duplication by writing everything in one request, that does both validations for creating and updating.
In the example below, you list the base fields like the first name and make some of them required.
But in your UpdateUserRequest, you’ll see a lot of duplicate code, but without the required validation rule.
The problem here is when change existing business logic, for example some logic in the unique email addresses; handle soft deletes. You might forget the second validation request, and break something in the other one.
What could be an alternative solution is moving all of your code into one class. And change the rules on the HTTP method.
- Keep everything in one class
- Less code duplication
Now we are redefining all of our validation rules, depending on the method POST. This way you can make the first name mandatory and handle the uniqueness an email address differently.
#2 custom messages
You could apply the same solution for writing custom messages depending on the method.
#3 Adding rules in your controllers
Another little hack making a copy of the validation rules (array) and add extra rules to it.
As you can see, there are more ways of handling validation and reduce the number of validation classes.