Move validations from controller to model


#1

Is it possible to move validation from the controller to the model?

  • What model method should be overridden?
  • And how then can I validate data in the controller?
class UsersController {
  async store({request, response}) {
    const validation = await validateAll(request.all(), {
      username: 'required|unique:users,username',
      email: 'required|email|unique:users:email',
      password: 'required'
    })

    if(validation.fails()) {
      return response.status(422).json(validation.messages());
    }

#2

I usually have validation inside validation classes.

But I think you can do

get rules() {
      username: 'required|unique:users,username',
      email: 'required|email|unique:users:email',
      password: 'required'
}

in user model


#3

+1 for validation classes


#4

Hey @sergey! :wave:

Nothing keeps you from adding rules getter to your model and doing validation in a hook (like beforeSaving).