php - Where to validate data Controller or Model in CodeIgniter
Get the solution ↓↓↓I know that the CI way of doing this is to validate against the rules in the controller, but I think this is not the ultimate approach. What would you recommend me to do follow the CI way or validate incoming data in the Model, so my model will always be protecting itself against bad data. My understanding of MVC is that controller don't have to keep any program logic, all the logic is implemented in the model. I will appreciate if you can explain in detail why both approaches are good and not and which one is recommended ?
Cheers
Answer
Solution:
There is no silver bullet.
Validation in the model protects you against programatic sources of invalidation. However, users do not get direct access to your models but only through controllers and ultimately through forms. Most of the time you need additional validation which is specific to a certain form or a certain controller and which is inappropriate in a model.
This argues for a layer of validation outside the model. Ideally you can create a separate validation object (maybe tied to a specific form) which is used by the controller. Occasionally you may need additional validation in the controller itself.
Validation is not binary. There are many layers of validation and different types of validation necessary in different contexts. You may need validation in both the model and the controller.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the payload is invalid.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.