Select dropdown with first option empty using Laravel Eloquent Collection
Laravel provides amazingly simple way to render the form select dropdown list from an Eloquent collection retrieved from a database table.
The first argument,
The second argument,
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
This can be accomplished from the controller by prefixing the eloquent collection as follows:
Alternatively, you can accomplish this directly from
Pretty simple, right?
// 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?
Leave a comment
If you sign up and log in:
OK, Sign me up!
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.