如何将数组值保存到数据库而不是 select 选项输入中的数组键?

How to save array value to the database instead of array key from a select option input?

在我的控制器中,我有一个选项数组 ($options=['a','b','c']),我在 select 输入字段的视图中使用它。我需要将值 'a'、'b'、'c' 保存在数据库中,而不是它们对应的键 (0,1,2)。 我怎样才能做到这一点? 控制器:

public function create()
    {
        $options=['a','b','c'];
        return view('example.create', compact('options'));
    }

查看:

<div class="form-group col-lg-4">
     {!! Form::select('option', $options ,null , ['class' => 'form-control']) !!}
</div>

如果您使用数组来填充 Form::select('selected_option', $options),您需要它看起来像这样:

$options = ['a' => 'a', 'b' => 'b', 'c' => 'c'];

然后,当表单值传回控制器时,Input::get('selected_option') 将收到值 'a''b''c'

获取所需数组的一种非常简单的方法是:

$options = array_combine($options, $options);,这将创建一个具有相同键和值的数组。