In my Resource Controller I have a store and an update function with nearly the same validation rules. Because my validation is a bit more complicated I created a Request for this.
But because the validation rules differ a bit, I have to create two Requests:
But so I have nearly the same array in two different places and if I decide to change it, I have to edit two different files. Is there a better way to do this?
I thought about creating an extra Request class which has an array with the common rules and the classes for the store and update Request inherit from this class and use the array from the base class to put together the validation rules.
But to add an extra class and inherit from it seems a little too much for me, just because one or to rules are different.
Another way I thought about was to only check the common rules in the Request class and add an extra validation in the store and update functions, but then the validation would be done in two different places, which would make the project more confusing.
I'm using Laravel version 5.8
I do suggest inheritance:
abstract class BaseRequest extends FormRequest {
public function rules() {
return [ /* common rules */ ];
}
}
class StoreRequest extends BaseRequest {
public function rules() {
return array_merge(parent::rules(), [
/* extra rules including overrides
]);
}
}
You can do the same for the update request as well. This creates a central place to manage the commonalities in the request.
This being said without actual code we can't really know what's most appropriate for your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With