Creating a Select Box Field

Problem

You want to create a select box in a form template.

Instead of using the <select> tag you want to do it the Laravel way.

Solution

Use the Form::select() method.

You can use a simple array.

{{ Form::select('age', ['Under 18', '19 to 30', 'Over 30']) }}

This uses the numeric index of the array for option values.

<select name="age">
  <option value="0">Under 18</option>
  <option value="1">19 to 30</option>
  <option value="2">Over 30</option>
</select>

Or you can use associative arrays.

{{ Form::select('age', [
   'young' => 'Under 18',
   'adult' => '19 to 30',
   'adult2' => 'Over 30']
) }}

This will use the keys for the option values.

<select name="age">
  <option value="young">Under 18</option>
  <option value="adult">19 to 30</option>
  <option value="adult2">Over 30</option>
</select>

Set the default option by passing a third argument.

{{ Form::select('number', [0, 1, 2], 2) }}

This produces the following.

<select name="number">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2" selected="selected">2</option>
</select>

Add additional attributes with a fourth argument.

{{ Form::select('number', [1, 2, 3], null, ['class' => 'field']) }}

Now the select field has the class attribute set.

<select class="field" name="number">
  <option value="0">1</option>
  <option value="1">2</option>
  <option value="2">3</option>
</select>

(Note: I added spaces and linefeeds in the example HTML output above for clarity.)

Discussion

You can also create select groups.

When the options argument contains an array with sub-arrays, then option groups are created.

{{ Form::select('feeling', array(
  'Happy' => array('Joyous', 'Glad', 'Ecstatic'),
  'Sad' => array('Bereaved', 'Pensive', 'Down'),
))}}

This produces the following HTML.

<select name="feeling">
  <optgroup label="Happy">
    <option value="0">Joyous</option>
    <option value="1">Glad</option>
    <option value="2">Ecstatic</option>
  </optgroup>
  <optgroup label="Sad">
    <option value="0">Bereaved</option>
    <option value="1">Pensive</option>
    <option value="2">Down</option>
  </optgroup>
</select>
comments powered by Disqus