Laravel中如何将多选框值以字符串形式存储到字段中
解决Laravel多选选择器值存储为字符串的问题
嘿,我看到你在Laravel里处理多选选择器的存储问题啦,别着急,这是新手常遇到的小问题,咱们一步步来解决:
第一步:修正表单中select的name属性
首先,你的多选选择器的name属性需要改成数组格式,这样后端才能接收到所有选中的选项值。如果不加上[],Laravel只会拿到最后一个选中的选项哦。修改后的视图代码如下:
{!! Form::open(['route'=>'diagnostic.store']) !!} <select class="form-control" multiple="multiple" name="diagnóstico_rela[]" id="person3"> <option selected="selected">orange</option> <option>white</option> <option selected="selected">purple</option> </select> <script> $("#person3").select2({ tags: true, }) </script> {!! Form::close() !!}
第二步:在控制器中将数组转为字符串存储
现在后端接收到的$request->diagnóstico_rela是一个数组,而你的字段是字符串类型,所以咱们需要用implode()函数把数组转换成逗号分隔的字符串(你也可以换成其他分隔符,比如|,根据自己的需求调整)。同时为了避免用户没选任何选项时出现错误,咱们可以加个空值判断:
$diagnosticRear_segment = new Rear_segment; $diagnosticRear_segment->conducta = $request->conducta; $diagnosticRear_segment->principal_diagnostic_id = $request->principal_diagnostic_id; // 将数组转为逗号分隔的字符串,处理空值情况 $diagnosticRear_segment->diagnóstico_rela = $request->has('diagnóstico_rela') ? implode(', ', $request->diagnóstico_rela) : ''; $diagnosticRear_segment->ultimo_ontrol = $request->ultimo_ontrol; $diagnosticRear_segment->próximo_control = $request->próximo_control; $diagnosticRear_segment->save();
额外提示:读取时转回数组(可选)
如果你之后需要把存储的字符串再转回数组用于展示或者编辑,可以用explode(', ', $diagnosticRear_segment->diagnóstico_rela)来拆分,比如在编辑页面设置选中状态的时候会用到这个操作。
这样处理后,多选的选项就会以类似orange, purple的字符串形式存储到你的字段里啦!
内容的提问来源于stack exchange,提问作者Juan Camilo Suarez Cantero
相关产品推荐
相关产品推荐

