Why are there 2 ways to Validate in Laravel 5.1? - validation

You can use Model Validation Rules and FormRequest/Request Validaiton Rules.
So there are Scenarios:
Form
Rest Create
Should you use a Model Validation regardless?
Why are there 2 methods?

Laravel provides a powerful Validation class that you can benefit from by using several approaches.
So, you can validate inside the model, and this works best if you need to centralize the logic at the model during creation or update. Also it works if you create Intermediate Models, or creating Models offline, for example Model to hold Reports.
Form Requests is a special way to handle Validation, you can handle the validation inside the Controller, or you can go slim Controllers, and move the Validation elsewhere. Form Requests is better when you are handling complex validation, or if you are using the same validation through different Controllers.
So the Validation class is the same, how you make use of it is up to you.

Related

Laravel place validation stuff

Laravel version - 5.0.0
Laravel offers so many ways to validate so I cannot choose what to use. Because no one of them suits my tastes.
What I want: full management of validation process. I want a class which:
has got rules property, but it I can modify them any time
can return break validation process if any rule fails; add rules to validator
has got custom messages
communicate with other classes which have got validate method as well as their own messages.
manage redirects and return values
Basically I do not want to extend validation class but simple use it. I think, form requests could do what I want. But now I do not understand their purpose. They are very poor in Laravel. Also, I do not want place all this in controller.
So, the only way is to create a custom class?

Input validation in MVC

I need a little help regarding design of MVC .
Most of the tutorials of MVC and CODEIGNITER are doing input validation in controller. Is it a good practice ?Suppose we implement REST or SOAP API then we are going to have different controllers, and for all those controllers I need to replicate my code. Later if any of the validation rule is changed, it will get rippled into all controllers. Shouldn't all the validation should be inside Model instead of Controller ?
One more thing I would like to ask. As I am trying to keep my functions as cohesive as possible, I am getting one to one relation between functions of model and controller. Is it ok or I am doing things wrong ?
Regarding doing input validation in Controller
Ans. Yes, that is the generally accepted practice in most MVCs. However, during the past few years, due to the advent of AJAX frameworks and more adoption of JavaScript, many UI validations get done in UI itself(called client-side validations). These are generally displayed as javascript alert boxes and do not allow user to go ahead unless he fixes these errors. So, I would say Controllers/View helpers are de-facto places where validations are done but you should consider client-side validations wherever feasible. It also saves you trips to the server.
If you expose the same as functionality as SOAP/REST
Ans. Now-a-days you can annotate the same controller methods to make them work as web service endpoints. So, your controllers can service both web-based requests and also SOAP/REST requests.
But one note of caution - your form-beans/backing beans should be very well designed. I have seen code where hibernate model objects are used as form-backing objects. This makes it tricky when you generate a WSDL out of the form-backing objects as hibernate model objects may have many linked entities and one ends up with very complex xml structures in the request/response.
But still, if you design your backing-beans as fine-grained, i.e. not having complex objects, then you should be comfortably placed in using your existing controller/controller methods as web service endpoints for both SOAP/REST.
Regarding the validations being inside Model layer
Ans. You can use this thumb rule to determine where to place which validations -
Business validations should happen in models/services
complex client validations, which are not feasible in client-side, should happen in controllers/view helpers
UI validations (formatting/empty checks) should happen via client-side/javascript validations
Regarding one to one relation between functions of controller and model/service
Ans. Its fine. Just remember to have one controller method talk to its respective model method. And if multiple models are needed to service a request, then that model method should act as an aggregator of information from multiple models i.e. the controller should contact its main model and the main model should contact other models.
Is it a good practice? In my experience yes.
One thing to keep in mind is that any given controller can display an number of different pages. For example, consider a "Dashboard" which could have multiple tasks each of which requires its own page.
A rough pseudo-codeish "Dashboard" controller might look like this:
class Dashboard extends CI_Controller {
public function __construct(){
parent :: __construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('somemodel_model');
}
public function index(){
//displays a task selection page with links to various tasks
}
public function admins(){
//some kind of interface to display and edit admin level users
}
public function users(){
//CRUD for dashboard users
}
}
With this controller the task selection page is opened with baseurl/dashboard, adminstrator's page with baseurl/dashboard/admins and user CRUD with baseurl/dashboard/users. Because each of these share the same Class, code needed by all/many of these pages (like validation) can be implemented in the constructor and/or with private methods. You probably already know all this. Keep in mind that AJAX responders can also reside in a controller using the same technique.
In regards to keeping the validation rules DRY and easing the work required for changes to rules CI can store sets of rules in a config file for easy reuse in multiple situations. Read about it.

Why use laravel route filters when outcome of a filter can be achieved in the controller?

What is the exact reason to use route filters in Laravel. Filter logic can be added to the controller and that way all the logic will be in the controller, not spread across multiple files.
Typically with the MVC pattern it is preferred that your Controller files are kept pretty lean. That means, they should only handle passing data to and from the Model and View files. Filters applied to routes allow you to apply specific logic, for example validating someone has the necessary roles to view the page, without fattening your controller.

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?
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.
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.
I wrestled with this for a while and settled on handling most of my validation in a validation service, based something along the lines of this. I can then have different validation rules based on the context.
As Nico mentions, validation in the model is good to avoid corrupt data, but I prefer thin controllers so I pass the functionality that would sit in controller into the service. This also has the benefit of being able to reuse the validation in different controllers/methods.
Why I prefer In-Model Validation: I've worked with both styles and each have pluses and minuses, but I prefer in-model validation. In our current app I don't see in-controller validation as an option, since we're altering our data in so many places (dedicated forms, inline edit, bulk edit, bulk upload, api, etc). I've never really worked with validation services (though they might be an option) but I personally like to keep logic as close to the model as possible, that way I know another developer won't bypass it. I also don't like adding lots of extra files on top of the MVC and basic Libraries folder because it just seems like more you have to think about organizing properly.
Issues with In-Model Validation: These are some things you need to consider to make In-Model work well. SOME OF THESE ARE ALREADY TAKEN INTO CONSIDERATION BY PLUGINS. I think other frameworks (CakePHP) already deal with these, but Laravel doesn't really.
Values that will be validated but not saved to the db (e.g.,
"accepted_agreement").
Many to many or belongs to many
relationships
Setting conditional defaults (not critical but
might want to think about at the same time)
Various form scenarios - sometimes you might need different validation
depending upon which form submits it. The form reference can be a
purgeable attribute for validation maybe?
How will you get back error messages (all in-model validation plugins handle this for you)
Different validation rulesets. Draft creation vs "real" creation. (Most handle this for you)
Ultimately, for simple applications that don't have lots of ways of interacting with the model, I'd say controller validation may be simpler, other then that I prefer in-model.

MVC2 DataAnnotations with Server-side validation

How do you validate an entity containing DataAnnotations without using the MVC library? Using Model.IsValid is fine when you're within the Presentation layer, but what about when you want to ensure the model is valid in the Domain/Business layer? Do I need a separate validation framework, or is there an easy way I'm missing?
Thanks for any help,
Mark
I suppose you mean ModelState.IsValid by Model.IsValid, right? Well, DataAnnotions don't depend on MVC at all, so you can always use the IValidatableObject interface.
Or perhaps the Validator class will be more appropriate, by using Validator.ValidateObject(object, ValidationContext).
I wrote my validation logic using plain c#, my business layer contains these validations and I use try and catch blocks throughout business layer. The presentation layer catches these custom exceptions so errors are shown on screen to the user. I only kept basic validation inside the data annotations e.g. [Required] mainly for ajax calls and to notify users to enter data in non nullable fields, that way my business logic remained in my middle tier, it remained consistent, it remained in only one place which I can refer to.

Resources