HTML Forms in Laravel

To add HTML forms in Laravel, you must install the HTML component. This component is part of a list of components that have been removed from the Laravel core framework. Even though this features have been removed from the main application, they are still maintained meaning that the components can be installed without worrying about compatibility issues.

Begin by installing the laravelcollective/html package through Composer.

$ composer require laravelcollective/html

Next, add the HtmlServiceProvider class to the providers array of the Laravel framework’s config/app.php file.

Collective\Html\HtmlServiceProvider::class,

Within the same file, add the two Facade classes into the aliases array.

'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,

With these installation steps followed, you can now use the form-related classes within your template files.

To add the form opening and closing tags, you can use the following markup:

{!! Form::open(['url' => 'foo/bar']) !!}
    //
{!! Form::close() !!}

You can also remove the curly brace and exclamation mark syntax if you echo out the code using PHP.

<?php echo Form::open(['url' => 'foo/bar']); ?>

You can specify a method array key to specify a form method. By default, it is assumed that a POST method is used.

<?php echo Form::open(['url' => 'foo/bar', 'method' => 'put']); ?>

If your form is going to accept file uploads, add a files array key.

<?php echo Form::open(['url' => 'foo/bar', 'files' => true]); ?>

Whenever you use Form::open(), a CSRF token form field will be added to your form, however if you need to specifically generate the token field, you can use Form::token().

To add a label, use Form::label().

<?php echo Form::label('email', 'Email Address');

The above code will add the following markup:

<label for="email">Email Address</label>

The syntax for adding some of the form inputs can be seen below.

// Add a text input with a name of 'username'
echo Form::text('username');

// Add a text input with a name of 'username' and a default value of 'John Doe'
echo Form::text('username', John Doe');

// Add a password input with a class of 'awesome'
echo Form::password('password', ['class' => 'awesome']);

// Add a checkbox and radio input that are both checked by default 
echo Form::checkbox('name', 'value', true);
echo Form::radio('name', 'value', true);


// Add a submit and button input
echo Form::submit('Click Me!');
echo Form::button('Click Me!', ['type' => 'submit']);

Note: This article is based on Laravel version 5.4.