Laravel: 3 mini-patterns with form validations

Photo by Ben on Unsplash

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.

Code of CreateUserRequest.php

But in your UpdateUserRequest, you’ll see a lot of duplicate code, but without the required validation rule.

Source of UpdateUserRequest.php

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.

Solution

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
Download source code at Github

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.

Conclusion

As you can see, there are more ways of handling validation and reduce the number of validation classes.

Senior back-end developer in Ghent who likes writing sometimes weird / creative solutions to a specific problem.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store