Data Validation in Laravel using Validator

Validation is a very important part of an app or a website because it verifies the incoming data. Previously we used to validate our data by putting so many if-else conditions in our file or by using JS. Now, we can do it by using Laravel Validator.
For example, if we are filling up a form and we forgot to fill out a field that is mandatory, we will mention that field name in the Validator and it will notify us about the field that is left.
Below is a simple example of how to use Validator:

First, use Validator at the top of your Controller file below the namespace.

UserController.php

Now, let the Validator know which field/fields you want to validate or are mandatory, like:
'{field_name_1}' => 'required',
'{field_name_2}' => 'required'
…and so on…

UserController.php

It will make an array of mandatory fields.
The data will be stored in the $error variable.
If we miss any field it will redirect us back to the same page with an error.
The Validator will show an alert containing the error. For that alert, we have to add a code in our blade file for the alert where it will be shown.

user_info.blade.php

And, the alert will look like this.

If we skip the “name” field:

If we skip both the fields, “name” and “email”:

Leave a Reply

Your email address will not be published. Required fields are marked *