Validation in Service Class or Controller?

I want to implement a Service pattern to keep my Controller thin. One thing I’m not sure is whether I need to put the validation in the Service or let it stay in the Controller.

For example, I have a UserRegistration controller, so I have kind of this register method:

class UserRegistrationController
     public function register($request)
          $credentials = array_get($request, ['username', 'email', 'password']);

          $validator = [
               'username' => 'required|min:5',
               'email' => 'required|email',
               'password' => 'required'
          if (! $this->validator->validate($credentials, $validator)) {
               // return and shows error


          // return and shows success

If I put the validation in the Controller, then in my Service class, I assume the credentials are correct, so I just store the user to the db.

class RegistrationService
    public function register($credentials) 
          $user = new UserModel;

          $user->name = $credentials['username'];
          $user->email = $credentials['email'];
          $user->password = hash($credentials['password']);


          // send welcome email 

Which one is the best practice? Make the Service class error proof or just leave it like above?

That validation isn’t hypothetically in the controller. Its fine the way it is in the first example. That is how it is done in Symfony and Laravel examples.

@oddz Thanks for your reply.
What I’m thinking is, if the Service class has no validation or any checking of $credentials parameter, then when it’s packed as a library somebody can misuse it by sending credentials without username. What do you think?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.