twiggy99's avatar

Should validation be in the controller?

I have a very simple input of one text field which posts to my controller's store method where I validate the request and then if valid will go on and store it in the database.

I have stopped after the validation because it doesn't feel quite right doing the validation and then model creation in the same method as in my mind it invalidates the SOLID principles of one task per method. I'm using custom validation messages as well so I'm already up to 7 lines of just validation code.

Am I overthinking this or should I be separating my validation somewhere else and then the store method should only handle storing the model to the DB?

public function store(Request $request)
    {
        $rules = [
            'name' => 'required|max:255|min:4'
        ];

        $customMessages = [
            'min' => 'This is not a valid name, make sure you are using your full name and not your access code.'
        ];

        $this->validate($request, $rules, $customMessages);
    }
0 likes
2 replies
MA's avatar

My suggestion is don't over complicate what can be done in a simple way! Are you ok with a few lines of code in your controller to validate one simple form field?

Even the Laravel documentation uses validation in the controllers.

Please or to participate in this conversation.