In Laravel up till now we are familiar with model-view-controller components , some routes and awesome blade syntax to decorate the views and write easy and short syntax for displaying data provided by the controllers. Now when we are talking about the application in day to day use, it will accept some data from users. In web-application data is collected using in html web-pages. form element have several other child where user can enter data and submit. Once user submit data it’s application’s responsibility to check whether submitted data is correct according to business rule or not. So data should be validated from application side before it stored in database or any persistence system.
To validate the data if i am writing a program in core PHP so i have to use empty, isset etc.. built in PHP functions and some custom logic with conditions according to requirements. But Laravel provides nice way to validate the data. Few methods and pass rules array to that methods. Let’s see an example.
Let you have a sign-up form for registering users to your application. So when user clicks on Sign Up links in your application, user will see below form.
Now once user clicks on submit button, this form should be validated against below rules.
- Email/Username must not be an empty
- Email/Username must be at-least 5 character long and it’s length is not more than 100 character.
- Email/Username must be a valid email address.
- Password must not be an empty
- Password must be at-least 5 character long and it’s length is not more than 15 character.
- City must not an empty
Let say in your laravel app there is two routes define in for this signup taks.
So when user click on Submit button in above form, postSignup method from AuthController will be executed. So let’s write some logic to validate form using laravel validation library function to satisfy above business rules. As i understand that you have enough idea about controller from my Laravel MVC Laravel MVC post so i am not writing complete controller here. I am just writting postSignup method.
Laravel provides awesome helpers for views especially for blade template enabled views. Do paste below code just above form tag.
and you will notice validation errors if validation fails. If everything is OK with validation rules and submitted data than you will see appropriate response from your controller. Not let’s understand the $rules array defined in postSignup controller method.
$rules array expects all keys are input fields from form and it’s values are validation constraints on that field. You can notice the ‘|’ symbol between two constraints. It says if you have more than two rules you can use ‘|’ symbol to add more rules or you can use array. To know more about validators that Laravel framework provides please visit this link http://laravel.com/docs/4.2/validation.