Moved code from controller to model