Select dropdown with first option empty using Laravel Eloquent Collection

 David

Laravel provides amazingly simple way to render the form select dropdown list from an Eloquent collection retrieved from a database table.


  // get all categories to be rendered in a select box (ideally from a controller)
  $categories = Category::orderBy('name')->lists('name', 'id');

  // in a view, render it using the blade
  {{ Form::select('category_id', $categories, Input::old('category_id', $blog->category_id), array('id' => 'category_id', 'style' => 'width: auto;') }}
Let's take a look at the Form::select() in more depth.
The first argument, category_id, is the value assigned to the name attribute of the <select> html element.
The second argument, $categories, is the array that will populate the <option>s elements within the <select> element.
The third argument is the default selected value from the <select> options, and finally the fourth argument is an array of keys/values that will be attached as <select> element's attributes.

Many times, we want to have an empty value as the first <option> value in the <select> element, such as <option value="">Please pick one</option>.

This can be accomplished from the controller by prefixing the eloquent collection as follows:

  $categories = ['' => 'Please pick one'] + Category::orderBy('name')->lists('name', 'id');

Alternatively, you can accomplish this directly from Form::select() on the view as follows:

  {{ Form::select('category_id', ['' => 'Please pick one'] + $categories, Input::old('category_id', $blog->category_id), array('id' => 'category_id', 'style' => 'width: auto;') }}

Pretty simple, right?
Go Back to List Page

Leave a comment

Name : Comment : view emoticons
Please consider signing up for our website.
If you sign up and log in:
  •   You can avoid the "I'm not a robot" captcha when commenting
  •   You can also avoid typing your name every time
  •   You can upload a picture for each comment
  •   You can change or delete your comment within 1 hour
  •   You can track all the comments you posted on this site
  •   You can read blog posts that are only open to members
  •   You can look up blogs using the search feature
  •   More privileges for our friends & families coming...

OK, Sign me up!

Emoticons are a great way to visually express how you feel.
However, there are times when unintended content is converted to emoticon because the content happens to have one of the emoticon symbols. That's why it's always good idea to preview your comment before posting and when you see this type of problem, you can indicate NOT to auto convert.