Laravel - Forms

Laravel - Forms

Laravel provides various built-in tags for handling HTML forms easily and safely. All basic HTML elements are generated using Laravel. To support this, we need to add an HTML package to Laravel using composer.

Example 1

Step 1 − Run the following command to continue the same.

composer require illuminate/html

Step 2 − This will add the HTML package to Laravel as shown in the following image.

Step 3 − We now need to add the above package to Laravel configuration file which is stored in config/app.php. Open this file and you will see a list of Laravel Service Providers as shown in the following figure. Add an HTML service provider as indicated in the box in the following figure.

Step 4 − Add aliases in one file for HTML and Form. Pay attention to the two lines indicated in the circled box in the following image and add these two lines.

Step 5 - Now everything is set up. Let's see how we can use different HTML elements using Laravel tags.

Form opening

{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::close() }}

Label element generation

echo Form::label('email', 'E-Mail Address');

Text input generation

echo Form::text('username');

Specifying a Default Value

echo Form::text('email', '');

Password Entry Generation

echo Form::password('password');

File input generation

echo Form::file('image');

Generating a checkbox or radio input

echo Form::checkbox('name', 'value');
echo Form::radio('name', 'value');

Generating a checkbox or radio input that is checked

echo Form::checkbox('name', 'value', true);
echo Form::radio('name', 'value', true);

Dropdown list generation

echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));

Create a submit button

echo Form::submit('Click Me!');

Example 2

Step 1 - Copy the following code to create a view called

resources/ views /form.php


<html> <body>
      <? php
         echo Form :: open ( array ( 'url' => 'foo/bar' )); 
            echo Form :: text ( 'username' , 'Username' ); 
            echo '<br/>' ;  
            echo Form :: text ( 'email' , '' ); 
            echo '<br/>' ; 
            echo Form :: password ( 'password' ); 
            echo '<br/>' ;
            echo Form :: checkbox ( 'name' , 'value' ); 
            echo '<br/>' ; 
            echo Form :: radio ( 'name' , 'value' ); 
            echo '<br/>' ; 
            echo Form :: file ( 'image' ); 
            echo '<br/>' ;
            echo Form :: select ( 'size' , array ( 'L' => 'Large' , 'S' => 'Small' )); 
            echo '<br/>' ;     
            echo Form :: submit ( 'Click Me!' ); 
         echo Form :: close (); ?>
   </body> </html>

Step 2 - Add the following line to app/Http/rout.php to add a route to view form.php


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

Step 3 − Visit the following URL to see the form.


Step 4 − The output will look as shown in the following image.