Creating a simple form in laravel

One of the most basic aspects of any web application is the form. Laravel provides easy ways
to build HTML for our forms.

Getting ready

To get started, we need a fresh installation of Laravel.

How to do it…

To complete this recipe, follow these steps:
1. In the app/views folder, create a new userform.php file.

2. In routes.php, create a route to load the view:
Route::get(userform, function()
return View::make(‘userform’);

3. In the userform.php view, create a form using the following code:
<h1>User Info</h1>
<?= Form::open() ?>
<?= Form::label(‘username’, ‘Username’) ?>
<?= Form::text(‘username’) ?>
<?= Form::label(‘password’, ‘Password’) ?>
<?= Form::password(‘password’) ?>
<?= Form::label(‘color’, ‘Favorite Color’) ?>
<?= Form::select(‘color’, array(‘red’ => ‘red’, ‘green’ =>
‘green’, ‘blue’ => ‘blue’)) ?>
<?= Form::susubmit(‘Send it!’) ?>
<?= Form::close() ?>
View your form in the web page, by going to http://{your-server}/userform (where
{your-server} is the name of your server).

How its work…

For this task, we created a simple form using Laravel’s built-in Form class. This allows
us to easily create form elements with minimal code, and it’s W3C (World Wide Web
Consortium) compliant.
First, we open the form. Laravel automatically creates the <form> html, including the action,
the method, and the accept-charset parameters. When there are no options passed in, the
default action is the current URL, the default method is POST, and the charset is taken from
the application config file.
Next we create normal text and password input fields, along with their labels. The first
parameter in the label is the name of the text field and the second is the actual text to print. In
the form builder, the label should appear before the actual form input.
The form select requires a second parameter, an array of the value in the drop-down box. In
this example, we’re creating an array using the ‘key’ => ‘value’ syntax. If we want to
create option groups, we just need to create nested arrays.
Finally, we create our Submit button and close the form.

Leave a Reply

Your email address will not be published. Required fields are marked *