KodeInfo | Learning resources for web and mobile development

Forms & Validation in Laravel

December 11th, 2014 12:33:54 in Forms & HTML , Validation by Imran Iqbal Comments(0) - Views(8118)
Tags : laravel, forms, templates, routes, form fields, form buttons, form security, Views, action, validation, rules, laravel forms, laravel validation, Laravel rules

In this tutorial we are going to learn how to build forms and how to target their routes using laravel framework routes . Let's get started with forms.

Opening Forms

When you are working on a form first we have to decide where we are going to send it. For that please take a look at our previous tutorials about how to use URL helper to generate action parameter URLs. Let's build a simple view with a form.

// app/views/form.blade.php

 

Let's add a route closure to display this form.

// app/routes.php

Route::get('/', function()
{

   return View::make('form');

});

Great now we have a route to display the form which we want it. Let's go and visit the URL and see what's coming there. It will show a form in the browser.

Laravel framework provides options to build a form in a different way using blade syntax and some methods. Let's see how we can build a form using in built methods.

// app/views/form.blade.php

{{ Form::open(array('url' => 'target/route')) }}

{{ Form::close() }}

To create our opening form tag using Laravel framework methods we used Form::open() method. This method accepts parameters in any array format like how we gave url route. We can give id,name,class etc parameters to this method. To close form we used Form::close() method.

Let's see what this new laravel methods rendered.

// app/views.form.blade.php

<form method="POST" action="http:://domain.com/target/route" accept-charset="UTF-8">

   <input type="hidden" name="_token"  value="sjjdhasd6786sd786ssdajsad"

</form>
 

Let's check the rendered form code, we just provided the target route. But in the form there was a lot of attributes like method, accept-charset and _token. By default laravel picks the method as a POST method and also charset as UTF-8 encoding for characters when submitting the form. But we can change these by our own choices also. let's see how we can change.

// app/views/form.blade.php

{{ Form::Open(array(
     'url' => 'target/route', 
     'method' => 'GET', 
     'accept-charset' => 'ISO-8859-1'
)) }}

{{ Form::close() }}

You can use in place of  GET, POST methods other HTTP  methods like DELETE, PUT etc. In the same way if we want to use the form for uploading files we have to set a new parameter called files as true in the same array.  When we add this new parameter to the Form::open() method, a new attribute enctype="multipart/form-data" will be added to the rendered code.  We can also add named routes and controllers actions to the Form::open() method using a special indexes called route and action.

// app/views/form.blade.php

{{ Form::open(array('route' => 'my_route')) }} 

{{ Form::close() }}

// app/views/form.blade.php

{{ Form::open(array('action' => 'MyController@myAction')) }} 

{{ Form::close() }}

Form Fields

Forms are not useful unless they provide a means of collecting data . Let's take a look at some of the form fields that we can generate using Laravel form builder library.

let's take a look at example which will explain different form fields provided by Laravel framework.

// app/views/form.blade.php

{{ Form::Open(array('url' => 'target/route')) }}
  
   //
   {{ Form::label('first_name', 'First Name', array('id' => 'first_name')) }}

   //
   {{ Form::text('first_name', 'Kode Info', ​array('id' => 'first_name')) }}

   //
​   {{ Form::textarea('description', 'Best Tutorial Ever') }}

   //
   {{ Form::password('secret') }}

   //
   {{ Form::checkbox('terms', '1', 'true') }}

   //Red
   {{ Form::radio('color','red',true) }} Red

   //
   {{ Form::email('email', 'test@gmail.com') }}

​   
{{ Form::close() }}

Form Buttons

Our forms are no good if we can't submit them. Let's have a look at the buttons we have available to us.

// app/views/form.blade.php

{{ Form::open(array('url' => 'my/route')) }}

   // 
   {{ Form::submit('send') }}

  //
  {{ Form::button('Send') }}

  //
 {{ Form::image(asset(''image.gif', 'submit')) }}
  
 //

Form Security

It's great if we receive data from our forms, but what happen when some external people tampers our data. We need a way to say that data is our application data. For that only laravel adds a special hidden input parameter called _token. This type of attack is called Cross Site Request Forgery(CSRF).

This token is kind of secret phrase for laravel. This token values is been created using secret value from our application config file.If we tell laravel to check for this value within our input data, then we can ensure that the data has been provided by a form that belongs to our application.

We could also check for the token ourselves by comparing it's value to the result of the Session::token() method, but laravel has provided a better option. If you remember our filters tutorial there we explained some default filters. Laravel has included csrf as a default filter.

// app/routes.php

Route::post('/post-form', array('before' => 'csrf', function()
{
   //handle form code
});

By attaching the csrf filter as a before filter to the route that will handle our form data, we can ensure that the _token field is present and verified. If our token is not present or didn't match then it throws an exception.

Form Validation

Till now we saw how to build a form using laravel form builders and form fields helper methods.But when users submit a form we are not checking whether that data was a valid data or not before submitting for data processing. This will give some serious problems to the application.

Let's go through an example to know how to do validation. Let's build a registration form with fields email, password and password confirmation.

// app/views/form.blade.php

{{ Form::open(array('url' => '/registration')) }}

   {{ Form::label('email', 'Email') }}
   {{ Form::email('email') }}

   {{ Form::label('password', 'Password') }}
   {{ Form::password('password') }}

   {{ Form::submit('Register') }}

{{ Form::close() }}

Now let's write Routes to show the form and also to handle to form post submission. 

// app/routes.php

Route::get('/', function() 
{

  return View::make('form');

});

Route::Post('/registration', function()
{

   $data = Input::all();

});

Now we in the second route we are able to get the post data after user submits the form using first route. But we are not validating the data. Let's write some validation rules for the data using laravel form validation rules.

// app/routes.php

Route::get('/', function() 
{

  return View::make('form');

});

Route::Post('/registration', function()
{

   $data = Input::all();
 
   $rules = array(
     'email' => 'required|email|unique::users',
     'password' => 'required|min:6'
   );

   $validator = Validator::make($data, $rules);

  if($validator->passes())
  {
     return 'Data was saved';
   }

  return Redirect::to('/');

});

Now in the above routes we wrote some validation rules for each form field using form validation rules in laravel framework. So we used required rules to say the field was required. unique::users rules says the field should be unique in users table in database. min:6 rule says this field should be minimum six characters length.

Now if validation fails we are redirecting the user back to the form. Suppose if we want to send the old form data to re populate in the form. We have to use withInput()  method. At the same time we can also send the error messages to show it to the user why the validation fails for that particular field. 

return Redirect::to('/')->withInput(Input::Only('email'))->withErrors($validator);

To show errors in the form after re population we have to loop through the $errors->all() method like below in form template.

@foreach($errors->all() as $message)

   {{ $message}}

@endforeach

If we want to show the error for a particular form field we can access the error message using the form field name like below

{{ $errors->first('email') }]

{{ $errors->first('password') }}

We can also create custom validation rules and messages using Validator class in laravel framework. Take a look at laravel docs to know how to do that. 

 

Thanks 

Kode Info

Author

  • Imran Iqbal
    Imran Iqbal

    Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Related

WHY USE A FRAMEWORK OVER PLAIN PHP

WHY USE A FRAMEWORK OVER PLAIN PHP
read more

GETTING STARTED WITH LARAVEL

GETTING STARTED WITH LARAVEL
read more

UNDERSTANDING LARAVEL STRUCTURE

UNDERSTANDING LARAVEL STRUCTURE
read more

UNDERSTANDING LARAVEL ROUTES

UNDERSTANDING LARAVEL ROUTES
read more

comments powered by Disqus