Request Validation using ValidatesRequest Trait in Laravel.

Q1. What is Validation?

Validation is used to protect or validate the request we’re getting from the user. Suppose we make a form and we’ve not used validation in the form so when a user submits a blank form then it might give error or exception and also we get blank data from the submitted form, so we use validation to protect the request. For example, we’ve added a field to get an email of the users and we want to get unique email id whenever user fill the field, so we use email validation in our page to protect the request.

Q2. How to Validate the Request?

To validate the request, we use a form to get input and validate it. At first, we make a simple HTML form to get input and it is a view file so we name it form.blade.php. See the below code of the form:-

In the form, we used an available object of message bank called error to pass the message in the form. It is predefined in all the view file. After that, we used the csrf token in the form and then our form code. In the code we also used value as old. why ?. To preserve the value we filled in the given field we use value as old. When we press the submit button then it calls the submitmyform page to give output.

To set the customise message we pass it as a 3rd parameter.

Now, we make function of our form as well as submitmyform in our controller, see below:-

Now we have to make the Route. But careful when making the route of submitmyform because the method is post for submitmyform so we write post in place of get. See the route below:-

Route::get(“myform”, “ProductController@myform”);
Route::post(“submitmyform”, “ProductController@submitmyform”);

Now See the output whether it returns a message when we did not provide value in the given field.

Now, When we fill 1-2 field and left other then what message returns. See below:-

When we fill all the fields, then what returns:-

If you want to get valid Email then add the below code in the controller. See below:-

See when we provide invalid email then what message appears:-