laravel - validate complex conditions on request inputs - php

Suppose I have a input with type='file'. I want this input to have a validation rule
based on its content. For example, it has specific content structure and if it doesn't, $validator->fails() returns true. I don't want to do that inside controller and make it ugly. What is the best and cleanest approach to do that?
I mean by "cleanest" the best place(directory/class/method) that the logic has should be located.
Thanks

You may wish to create a form requests. Form requests are custom request classes that contain validation logic.
Laravel then automatically passes the user's input into the request before parse through the POST route, meaning our validation can now be moved entirely into FormRequest objects and out of our controllers and models.

Related

Should I implement user data sanitization/validation as middleware?

I'm reimplementing my user management system with Slim, and I'm trying to figure out where I should do user data sanitization/validation. I've been reading about middleware, and I'm wondering if this is an appropriate way to implement data validation.
My plan for validation is to use a validation schema (a simple JSON file) for each request that contains some user data (i.e., forms). However, different forms will obviously use different schema, and there may be some types of validation that cannot be handled by the schema alone.
Thus, any middleware I implement will have to decide which schema to use based on the route. Plus, some routes will require additional validation logic beyond that represented in the schema. This to me sounds like the wrong approach though - isn't middleware supposed to be fairly "generic", performing the same logic on every request/response?
Another approach would be to have some sort of validation object that I initialize in each route with the appropriate schema, and then into which I inject my Slim app.
Which would be the more sensible approach?
Using global middleware doesn't make sense as you end up coupling every endpoint's parameter list together.
The two options I would consider are:
Implement as route middleware so that you can have different filtering/validation for each endpoint.
e.g.
function fooFilter() {
// filter/validate GET variables here and set back into request.
}
$app->get('/foo', 'fooFilter', function () {
// "controller" logic
});
The advantage of doing it this way is that your controller logic doesn't need to be cluttered up with validation stuff as that's already been done.
Filter/validate within the controller logic. The main advantage here is that you can more easily audit if a GET variable is being used without being filtered/validated first.

Laravel 5 API request validation

I'm working with Laravel 5 API. I have a few methods with similar request parameters
For example to check the licence status or get the settings file you need to provide the ?serial=licence_serial_number parameter.
I need to return 400 error code, when the user didn't provide the serial parameter, and 403 error code, when the user is trying to get information about the licence of another user.
What is the best practice to organise validation and error handling of these kind of requests?
Should I make a middleware to check if the user has provided ?serial?
Or should I make a different Laravel 5 FormRequest class for every method?
Or should I validate it directly in a controller with:
if (..) {return response()->json([..], 400);}
$request->wantJson(), with a request with Header Accept=application/json Will tell Laravel to return json validation error instead of goback with errors
Middleware will probably be the best choice but you could also use the Request method.Inline validation is a bad practice as its ignore the most basic rule of programming - Dont Repeat Yourself.
In case you decide go for the request option you aren't supposed to create the authorize method for each class,instead create 1 parent witch will handle this and the other sub classes will just have the rules method.
It depends on a few things acctualy:
If your always validating the same thing for all requests: Go With a Middleware Solution.
But if some or multiple requests validate different things then I would advise on using the new FormRequest from Laravel.
It handles the validation for your request perfectly, and also allows you the define the error responses per request.
Also a middleground is an option, Let middleware validate the thing that needs to be validated always. And FormRequests to handle the variable validation.
If you have similar FormRequests, consider using inheritance to prevent code duplication like a good SOLID programmer :-)

Passing data from an action to Filter - Yii

I'm looking for a suggestion on how to solve an issue I have. I have a filter that executes a DB check on the postFilter function. The filter basically sees if an email should be generated and send out a template set up by the site admin. This function is working as expected.
The issue i have is there are some actions that i need to pass specific data to the email template that is only exposed within the action. My initial idea was to assign the needed values to a system parameter in the form of an array that could be accessed from filter function. The issue with this would be documenting each action that passes extra data.
I just wondering if there is more elegant solution... I would like to keep the system as flexible as possible for the user so if there was a way the user could setup a catch on the preFilter action that could then pass the needed information to postFilter.
Thanks all.
Since the data is generated within the action there's no avoiding the fact that the action has to cooperate somehow in order to make the data available to whatever code ends up sending the email. Therefore I can't see how it would be possible to not have to document that "action X exposes data Y".
A very simple but at the same time quite adequate solution would be to have a pair of setContextData / getContextData functions on the base controller; actions set the data and the postfilter reads it.

share annotaion validation rules between form and persistence

one "simple" question: http://mwop.net/blog/2012-07-02-zf2-beta5-forms.html
is it possible to use the zf2 zend form annotation validation rules without using zend form, so i can share the validation rules between a model validator (e.g. using for check if the model is correct before persisting it) and the zend form validation?
if my "name" should be not empty and between 5 and 20 characters, it is the same rule for the form and the model.
i hope i pointed it out clearly
Roman
Well, since all data that the models are getting would be from user input or the database, you shouldn't need to test the models itself, too. THe data inside the database should be correct!
IE: trust your own data but not the users?
But if you still wanna do that, i guess you could build the form with the AnnotationBuilder, then get the InputFilters from the Form (im sure there's a method, maybe on per-element-basis) and then use those inside your models - but as my first paragraph implies, i see this as a quite useless point :)
As for multi usable input filters, best thing would be to write own classes extending Zend\InputFilter\InputFilter on a per model basis. When you build your form then you can attach that class as the filter definition via $form->setInputFilter($myModelInputFilterClass) and you could also call that class inside your models to run your data through those filters. I haven't done this manually but it should work.
The only pitfall i guess might happen if you run into required statements. Checking on a per element basis, i don't know if that will work, too. As the InputFilter checks against all given filters. Though if you import a full CSV-Sheet or something you'd have a populateFromCsv() function or something that then checks all data anyways i guess.

How to avoid bloating the controller code in CodeIgniter?

Controllers are there in MVC pattern to process user input and output. So, input validation and response preparation should be done in a controller.
For instance, I have a controller method "save" which:
looks for input data
runs a validator on the data
if inputs are valid, loads an appropriate model, sets its fields to input values, and calls its save() method
if inputs are invalid, prepares data to re-load the edit form, shows the form
All this sequence creates quite a mess of linear code. I'd like to separate it somehow. Do I move the validation part to a model? Sounds wrong? Do I create a special "library" class to handle inputs?
In Asp.Net MVC this would be better as they have implemented the "object binder" pattern. Hence, the validation and model field binding goes away and controller gets much lighter. Is there something similar for CodeIgniter?
It is not widely accepted that controllers do validation, I do them in model as per "keep your models fat, controllers thin and views dumb".
It depends on the business logic what is a valid phone number and so on, so it only makes sense for me to have it in model.
I would do exactly as you have eluded to and put as much logic into your models as possible. Controllers really should, imo, be used for initiating services and preparing data for views.
You should as much code reusable, ie validators, filters etc..

Categories