Setting a Laravel Select Box Default Value

Blade Forms

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at November 4, 2015 8:48 pm

Populating a Laravel select box is easy, but how do you set a default value?

I use the LaravelCollective/HTML package for form generation in all of my Laravel projects, simply because it makes creating and populating forms so incredibly easy. For instance, here's an example of a select box created using the LaravelCollective/HTML package's Form::select helper:

<div class="form-group">
  {!! Form::label('Category') !!}
  {!! Form::select(category',
  \App\Category::lists('name', 'id'), 
  null, 
  ['placeholder' => 'Category']) !!}
</div>

See that null value, passed in as the Form::select helper's third parameter? It is a placeholder for the default value, and setting it to null will cause the placeholder value to be used as the default setting. However, you can change it to automatically be set to anything passed into the set of available values by using the associated label (in this case a Category record name:

<div class="form-group">
  {!! Form::label('Category') !!}
  {!! Form::select(category',
  \App\Category::lists('name', 'id'), 
  "Debugging", 
  ['placeholder' => 'Category']) !!}
</div>

Once set, Laravel will automatically set the select box option value to the ID associated with the "Debugging" category.