Forms are an important part of any web-based application. They help control the flow of the
application which allows us to receive input from our users and make decisions that affect the
functionality of our applications. They are also my least favourite thing in the world to write.
Fortunately for me (and you), Laravel’s form class takes care of a lot of the hard work for us
by providing useful methods for generating common form elements. Let’s use the form class to
create a simple web form in one of our views.
6.1 Creating Forms
1 // form.php9 <input type="password" name="password" id="password">
11 <!-- login button -->
12 <input type="submit" value="Login">
Great, it worked! I mean of course it did! Let’s go over the form line by line to see how it works.
On our first line we have the Form::open() method which creates a form open tag for us.
1 <?php echo Form::open('my/route'); ?>
The first parameter to the method is the URI we wish to submit the form to. The second
parameter is the METHOD used to submit the form, if you don’t provide a method as a string
Laravel will assume that you want a POST form, which is the most common usage.
The third parameter is also optional. You can pass an array of attribute => value pairs to
add extra attributes to the <form> tag. For example, if you wished to target the form with some
element an id.
To submit a form to a secure URI (https) you will need to use the open_secure() method instead
of open(). It accepts the same parameters.
If you wish to be able to have files uploaded from your form then it will need to use
multipart/data We can use open_for_files() instead of the open() method to accomplish
this. This method also accepts the same parameters.
Finally if you wish to submit to a secure URI and have files uploaded you will need to use
the open_secure_for_files() method. This once again accepts the same parameters and is a
combination of both open_secure() and open_for_files().
2 <?php echo Form::open('my/route'); ?>
4 <!-- username field -->
5 <?php echo Form::label('username', 'Username'); ?>
6 <?php echo Form::text('username'); ?>
8 <!-- password field -->
9 <?php echo Form::label('password', 'Password'); ?>
10 <?php echo Form::password('password'); ?>
12 <!-- login button -->
13 <?php echo Form::submit('Login');
15 <?php echo Form::close(); ?>
Take a moment, stare at the form source, you have never seen a form so clean. Say it out loud
to yourself, go on.. I will wait.
I have never seen a form so clean.
You are right, it’s beautiful. Let’s have a look at the generated source to make sure I’m not just
teaching you wrong, you know, for fun?
1 <form method="POST" action="http://mysite/my/route" accept-charset="UTF-8">
3 <!-- username field -->
4 <label for="username">Username</label>
5 <input type="text" name="username" id="username">
7 <!-- password field -->
8 <label for="password">Password</label>