Laravel Validation using The Factory Method

Abdulmalik
3 min readMar 30, 2023

--

Laravel Validation using The Factory Method
Photo by Alexander Tsang on Unsplash

Working on a project with potential signs of becoming larger can cause one to overthink, especially when you have to repeat implementations so often or you fail to adhere to certain patterns.
One of those things you need to keep away from your controllers (as much as possible) when building APIs is the business logic. But what about validation?

Validations usually take few lines at the beginning of controllers or more depending on the complexity of your validation cases. One of those interesting mechanisms Laravel uses to handle validation is through your Request class, right before your controller handles your request.

Handling validations with the Request class is great, but the process of creating one class per request handler (or controller) seems like an overkill, especially when it’s only just for validation. What about a Validation class per Controller Class (not method)?

What is the factory method?

According to refactoring.guru, factory method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
Factory method is one of the classes of factory design patterns and it is useful when you want to dynamically instantiate classes based on certain distinct properties. In our case, we’re grouping validation rules based on controller classes and we’re injecting exactly 1 validation class per controller class.

Validation folder containing validation classes

In the picture above, we have a dedicated validation folder for all our validations and each file houses a group of controller based validations.

The AbstractBaseValidation is an abstract class that allows you set your list of rules within a controller.

The validate function takes in the key of the target validation rule and implements validation using Laravel’s helper request() method.

Other files (asides the BaseValidation class), also follow the same pattern.

The next step would be to inject the validation class into your controller or service through the constructor.

Injecting validation class into the vehicle controller
Line 28 implements validation using rule key

And there you go!

This is subjective and there’s no hard-and-fast rule, Please feel free to share how you handle validation within your application in the comment section.
Thanks for reading.

Happy coding!

--

--

Abdulmalik

I've recently embraced the culture of reading, since I discovered it's equivalent to hundreds of mentors.