Validation is the process of checking the incoming data. By default, laravel provides the base controller class that uses the ValidatesRequests trait to validate all the incoming Http requests.
Let's understand the validation through an example.
We will create an application in which we add the name of the student.
composer create-project laravel/laravel=5.8 student_app -prefer-dist;
The above output shows that the student_app project has been created successfully in the xampp/htdocs directory.
The above code creates a table 'students' that has four columns (id, name, created_at, updated_at).
Data available in the user table:
php artisan migrate;
Output of the above code is shown below:
As we know that the URI of the index() method of a StudentController is '/student', so when we hit the url 'localhost/student_app/public/student', it calls the index() method. The index() method returns the view of the index.blade.php file, which is shown in the above screenshot.
When we click on the 'Add Students' button, and then we refresh the page, the output would be:
As we can see in the above screenshot that the 'Himanshu' is added in the students list, which means that the 'Add Students' button is working correctly.
Sometimes the situation arises when we do not enter any data, and we press the 'Add Student' button; this requires validation. We added the validation code in the store() method that validates the 'name' field, but we have not displayed any error message. To display the error message, laravel has provided the error variable that displays the error message. It can be used as:
After adding the above line in index.blade.php, the code of index.blade.php file looks like:
We can also restrict the characters in the textbox field. If we want to enter atleast 5 characters in the name field, then we can use the min field in a validate function.
Next TopicLaravel File Upload