How to Create a Select Box Field in Laravel

A <select> tag is used to create a drop-down list. It allows user to select one or more options from a pre-defined set of values. a <select> tag comes in handy when you want to display many options within a limited space.

In this tutorial, we are going to create a Select box using Laravel’s Form::select() method.

Useful Read : Creating a Hidden Input Field in Laravel

To create a select box you can use the following code. First parameter (occupation) is the name of the select box and second parameter is an array which consists of options used within the drop-down list.

{{ Form::select('occupation', ['Web Developer', 'Doctor', 'Lawyer', 'Accountant']) }}

The above code will create following HTML output,

<select name="occupation">
  <option value="0">Web Developer</option>
  <option value="1">Doctor</option>
  <option value="2">Lawyer</option>
  <option value="3">Accountant</option>
</select>

You can also use an associative array to assign custom values to <option> tags.

{{ Form::select('occupation', [
   'information technology' => 'Web Developer', 
   'health care'            => 'Doctor', 
   'law'                    => 'Lawyer', 
   'commerce'               => 'Accountant']
) }}

The above code will generate following HTML output,

<select name="occupation">
  <option value="information technology">Web Developer</option>
  <option value="health care">Doctor</option>
  <option value="law">Lawyer</option>
  <option value="commerce">Accountant</option>
</select>

To set a default option you need to pass a third parameter.

{{ Form::select('occupation', ['Web Developer', 'Doctor', 'Lawyer'], '2') }}

This will output the following,

<select name="occupation">
  <option value="0">Web Developer</option>
  <option value="1">Doctor</option>
  <option value="2" selected="selected">Lawyer</option>
  <option value="3">Accountant</option>
</select>

You can also add HTML attributes like class or id by passing the fourth parameter to this method,

{{ Form::select('occupation', ['Web Developer', 'Doctor', 'Lawyer'], null, ['class' => 'someclass', 'id' => 'someid']) }}

The above code will produce the following HTML output,

<select name="occupation" class="someclass" id="someid">
  <option value="0">Web Developer</option>
  <option value="1">Doctor</option>
  <option value="2">Lawyer</option>
  <option value="3">Accountant</option>
</select>

 

0 Comments

Leave a Comment.