Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Model validation vs Controller validation

It seems like official way to validate models in Laravel 4 is through Validator in Controller? Can somebody point out why is it so?

Wouldn't it make more sense to implement validation in Model?

like image 947
Slava V Avatar asked Jul 01 '13 09:07

Slava V


People also ask

Should validation be done in controller or service?

As a general rule of thumb, I would say that business logic of this sort should be in the service. Controllers should be light-weight and pass on requests. Further, there may be other clients of your service, not just controllers, so this allows you to keep validation in one place. Save this answer.

How many types of validation are there in laravel?

Each form request generated by Laravel has two methods: authorize and rules .

What are the different types of input validation?

There are two different types of input validation approaches: whitelist validation (sometimes referred to as inclusion or positive validation) and blacklist validation (sometimes known as exclusion or negative validation).


2 Answers

I prefer the Ardent package for making validation of models as smooth and minimal as possible. To me it makes more sense to have the validation rules in the model as well.

It will return false when $model->save() is called and validation fails, then you can get the error messages through $model->errors()->all() for example.

like image 54
Niklas Modess Avatar answered Sep 20 '22 13:09

Niklas Modess


It does make sense to have validation in the models, but this validation should only be there to make sure you don't save any corrupt data.

The Validator is in the Controller because it's used to handle Input, and generate Output. If you would do the validation in the Model then you either have to return false, and show the user the most random of error messages about invalid data. You could also return some kine of array containing all the errors that are generated, but that's something a Model shouldn't do. Or you could throw an Exception, which is something that should be done when a model tries to consume invalid data, but it kills the application, which is not the wanted solution for a form validator.

When doing the form validation in the Controller, you can do everything you want with the error messages, without changing the purpose of a Model.

And in your model you can do a validation to make sure you didn't make a mistake, which will corrupt your database. Because if this happens the application should shut down.

So to put this in a real answer to your question: Validation in the model makes sense to avoid corrupt data, but if you want to give feedback to the user about invalid input, it should be in the controller.

like image 44
Nico Kaag Avatar answered Sep 18 '22 13:09

Nico Kaag