Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
George Anderson
Frontend and backend development guru, lover of all things computer... and cats! Hopes to make your coder life a breeze by sharing some tips and tricks of the trade.

Request input validation is an important aspect of building any application, ensuring that the input matches values expected to complete a given operation. Laravel is a PHP web framework, following the MVC architectural pattern. It provides several built-in methods, which help in handling request input validation.  In this article, we will be looking at some of these methods.

We will be considering four different methods that we can use to perform validation in Laravel, as well as how to create custom validation rules.

Configuring the Development Environment

For this tutorial, I will be using the Eclipse IDE with the CodeMix plugin installed. To install CodeMix into your Eclipse environment, please follow the installation instructions on this page, or get it from the Eclipse marketplace. You can install the Laravel extension using the CodeMix extension browser. For this tutorial, we are using Laravel artisan and Laravel blade snippets extensions respectively. Click the image below to see a recording.

In order to proceed with this tutorial, you must have the following installed:

  • PHP can be installed in several ways, like using the PHP installer or an all-in-one package, such as XAMPP, WAMP and so on (which gives added functionalities, for instance, setting up Apache, phpMyAdmin etc.)
  • You also need to install the PHP dependency manager, Composer, which will be used to install the various dependencies needed by Laravel.
  • Finally, the Laravel installer is required to create a new project; it can be installed globally using Composer in the terminal, with the command below:
CodeMix 2 is here to further improve your new amazing Eclipse IDE experience with the best of VS Code tech and add-on extensions built for Code OSS. Enjoy its ready-to-go technology packs and get superb support for JavaScript, TypeScript, PHP, Python, and other languages.

Getting Started

Now, open the integrated Terminal+ in CodeMix 2.0. alternatively, it can be opened using the command Ctrl + Shift + P) as shown below.

Finally, the Laravel installer is required to create a new project; it can be installed using Composer in the Terminal+, with the command below which installs Laravel for global usage. In the opened Terminal+ panel enter the following command:

Now again in the opened Terminal+, we will create the Laravel Project using the following command:

Development

In order to perform validation, we need inputs. To provide input, we would create a form which would receive user inputs and post it to the server. The form would also provide a way for us to give feedback to the user on invalid inputs. We create this form in a new file called user_form.blade.php in the resource/views directory. The file should contain the code below:

In the code snippet above, we provided a form where all input has been conditionally styled to include the class name is invalid if there was an error whose name is equal to that of the input field, as well as render a span containing the error message for that input.

The form posts to a named route which we would define in the routes/web.php file, where we would also create a route to show the form, as demonstrated below: 

Next, we need to create the controller that we referenced in the routes file. We do this using the following artisan command in the opened Terminal+:

Now we need to create a function to render the form in the view we had created, as well as a function that receives the inputs and validates them. We do this by navigating to the app/Http/Controllers/UserFormController.php file we had created, and edit it as shown below:

Validation Methods

  • Using the in controller validator
    The most common method of validating in Laravel, is the validator in the controller (which is available through the ValidatesRequests trait used by the base controller in Laravel).  Custom error messages could be passed as the final optional parameter.

    Here we pass the request input to the validate method of controller with an array of rules for each input, with the key of each element in the array matching the name of the input file. The name input validation fails if the name input value is empty. The email input validation fails if the input isn’t a valid email, or if there is an entry in the user table email column with the same value, or if the length of the string is more than 255 characters. The password entry passes if there is another field with that name (in this case password ) with a suffix _confirmation (i.e. password_confirmation) and if their values match, but fails otherwise.
    The images.* key accepts an array of files, with the only permitted file extensions listed, using the mimes (which takes a comma separated parameters) validations rule. In validation, arrays are indexed using dots (.) (for example images[1] would be written as images.1 or files[‘new’] as files.new). The asterisk (*) is used as a wildcard i.e. to match every file in the files array.

    If validation fails, the request is automatically redirected back along with the errors and old values, which are then rendered in the view, just like we did in the previous view snippet.

  • Using the in-request validator
    This is very similar to the previously discussed method. It can be found in the request object injected into the function by Laravel (using dependency injection). Below is how we would use this method:
  • Manually create a validator
    In this case, validator objects are manually instantiated (created). This gives us more control over what to do when the error fails. We could choose to redirect the user to a different route or perform several other operations before deciding to redirect the user. We can also decide to just perform the redirection back by calling the validate method on the object.  Custom error message can be passed as an optional third parameter.
  • Using form request
    This is done by creating a class which extends the Illuminate\Foundation\Http\FormRequest class and then specifying the rules, as well as how to determine who can make the request. This is a good way to abstract the validation process, especially for forms with a large number of entries. We can also specify the error message for each field. We can generate the class file using the artisan command below:

     This generates a file in the app/Http/Requests directory called UserFormRequest, which we would edit to look like this:

    The UserFormRequest class is then used instead of the Request class in the controller, as shown below:

Creating Custom Validation Rules

Laravel provides several validation rules; however, we sometimes need to validate inputs in a way unique to the current application we are building. For instance, in building a staff management system, we may want to ensure that the staff ID conforms to a particular pattern, for example, three alphabetic characters followed by five numeric characters. In such cases, we would need to create a custom validation rule. Laravel provides ways to do just that. We can either create new rules or directly register them in the app/Providers/AppServiceProvider.php boot function.

We can create a rule class using the artisan command below:

Which will create a file StaffId.php in the app/Rules directory. We can apply the rule created by passing an instance of the rule as part of a rules array for the input, for example, given the rule definition below:

Which will ensure that the value of the input starts with three alphabetic characters, followed by five digits, which brings the length to a total of eight characters.

Tip: Press Ctrl + P to use Quick Open to open any file by its name, as shown below:

It is then applied as shown below:

The other way to create a new rule is to enter it in the AppServiceProvider.php file using the Validator::extend method. Also, customizing the error message for this method is done by using the Validator::replacer method. To achieve the same end result as the previously illustrated custom rule, we proceed as shown below:

This can be applied as part of the pipe | (i.e. rule_one|rule_two:parameter|…|new_rule) separated string of rules in every method previously discussed, for example:

Conclusion

Validation is a critical part of web development. Poor validation is a major cause of system breakdown due to invalid input, and it usually results in developers handling multiple exceptions, ultimately leading to complex and less readable code. In Laravel, there are many validation rules (too many for us to cover here, but refer to the Laravel documentation to check them out) that aid in quick development, which is made even more efficient with CodeMix. There are also multiple ways of expanding the rules set, as well as applying them. This helps us write robust applications, as we can work on input without having to worry about exceptions due to invalid user inputs.

Related Posts

A Day with Dani: Angular Coding with Angular IDE +... Now that I’ve acquired a pretty good amount of knowledge with Python, I have decided to test the waters of Angular development. Already being familiar with CSS, HTML and JavaScript, I was advised to start looking into learning this language. I love working with web technologies, so I went ahead and took an Angular crash course to get me started. Af...
A Day with Dani: Python Support at Its Best Python support provided by CodeMix has proven to make a world of difference to me. In this blog, I will highlight some of my favorite aspects.Intelligent Code Completion and MoreCodeMix IntelliSense tools are amazing, hands down. As shown below you can see an outside Python library import in another Python program I created that analyzes the semant...
CodeMix – A Genesis At Genuitec, we have been building developer software for nearly two decades. Our goal is to provide customers with access to seamless tool stacks, regardless of where the technology originates. However, delivering timely solutions in a rapidly evolving language and technologies world is critical to modern development and continues to be our larges...
MyEclipse 2018: Java 10, Java EE 8, Code Mining &#... MyEclipse 2018 is here, and as you will see and experience, this release has been well worth the wait. We've got Java 10 support, Java EE 8 across our enterprise wizards, and core improvements from building on Eclipse Photon. New features include code mining for efficient source analysis, an enhanced startup experience, a new dark theme, and much m...

Posted on Oct 11th 2018