Laravel 5: HTTP Layer – Validation

Laravel 5: HTTP Layer – Validation

Validation: checking if incoming data adheres to set rules.

All validation rules can be found here.
More on Laravel docs page here.

This is some base class:

Add validation directly to method of your Controller

Add validation directly to method of your Controller where you process incoming form (etc.) data.

method 1: automatic redirection

Above allows to validate form fields and automatically redirects back to form page with errors and form input.

method 2: use Validator and redirect back manually

method 3: use Validator and redirect back automatically

When you chain validate() method, redirect and data/error collection will be done automatically.

Add mulit-lang “nice” validated field names

Out of the box validation returns errors with standard form field names.
e.g. if password is not validates and password field is called ‘password’, it will be used in error message.

It looks good (mostly) in English, e.g.:

… but in other languages may not look good, e.g. in Polish:

Word ‘password’ does not exist in Polish … and probably most of other languages.

There are two ways to get this fixed, so local languages is fully implemented.

way 1: overload method from Validator class (local approach):

You do this in your controller, where you validate input.

This is how it is done:

Problem with this approach (or advantage) is that it is done locally and it will not apply to another validator in another form.

way 2: global approach

This will work in all validations with that field.

In language translation file:

… use this array (on bottom of file), to translate all fields.
(sample of Polish mapping in Polish translation file).

Being a global solution, it will pickup any defined/mapped fields in other form validations, in different Controllers.

In this case your controller validator method may look something like this:

… since all mapping is delegated to language translation file.


Create validation request class
method 4: Create validation request class

If you have a lot of validation, of do not like to overload controllers, this seems like a sensible solution to unload some code.

create validation request class

validation class method: rules

This class close validation rules, refactored here from controller (samples above).

validation class method: authorize

Here, you authorize access to resource.

e.g. here you can check if user is authorized to add to database, or see  something.
See below how to put this to work – how to fire this class.

How to fire /  put to work validation request class

You fire that class by type hinting it in a method that requires its validation / authorization services.
So, pretty much it is the same thing as with methods used in in controller validation, just rules were moved elsewhere
lo lighten the load.