Laravel - Populating Select List with Derived Valu

2019-03-06 14:33发布

I have an Eloquent model (Presenters) that has three columns: id, first_name and last_name. What I want to do is populate the select options so that the id is the value, and the first_name . last_name is what is displayed.

For instance, if I had these presenters:

id, first_name, last_name
1, Billy, Bob
2, Jose, Cuervo
3, Puff, the Magic Dragon

I want something similar to this output:

<select name="presenters">
    <option value="1">Billy Bob</option>
    <option value="2">Jose Cuervo</option>
    <option value="3">Puff the Magic Dragon</option>
</select>

I know that if I only care about the last name or first name in the select list, I can do this:

{{ Form::select("presenters", Presenter::lists("first_name", "id"), Input::old("presenters"), array( "class" => "form-control" )) }}

There are many questions already regarding populating select inputs for models in Laravel, although I haven't found one yet that shows how to populate a select input where a derived value is to be shown in each of the options rather than just a single column.

Can I use the lists method to populate the select element, or will I need to populate my own array of values / option texts?

标签: php laravel-4
2条回答
贼婆χ
2楼-- · 2019-03-06 15:34

You've provided the answer, look at the PaulDM reply

Just adapt it, hope it works for you:

// your eloquent model ...
public static function listPresenters() {
    $ret = [];
    foreach (self::all() as $presenter) {
        $ret[$presenter->id] = "{$presenter->first_name} {$presenter->last_name}";
    }
    return $ret;
}
// your eloquent model ...
查看更多
姐就是有狂的资本
3楼-- · 2019-03-06 15:38
Presenter::select('id', DB::raw('CONCAT(first_name, " ", last_name) AS full_name'))->lists('full_name', 'id');
查看更多
登录 后发表回答