如何在Laravel 5.2中存储多重选择值 [英] How to store multi select values in Laravel 5.2
问题描述
我有一个存储新闻的表格.
I have a form which stores News.
这里我使用的是Multiselect,我想将表中所有选定的选项另存为字符串,例如Users,staff,cinemahall.
Here I am using Multiselect and I want to save all the selected option in the table as say Users,staff,cinemahall as a string.
我存储值的控制器功能是
My controller function to store values is
public function store(Request $request)
{
$input=$request->all();
General_news::create($input);
return redirect()->back();
}
此函数存储所有提交的字段,但对于多选功能,它仅存储最后一个选项,即Cinemahall
This function store the all submitted fields but for multiselect it stores only last option i.e cinemahall
提交表单后,所有选择的选项都会显示,但未正确保存在数据库表中.
When form is submitted all selected options are displayed but it's not saving in database table properly.
帮我解决这个问题.
推荐答案
确保将name属性设置为数组
Make sure you set the name attribute to an array
<select multiple="multiple" name="news[]" id="news">
将其存储为用逗号分隔的字符串
To store it as string separated by commas
$news = $request->input('news');
$news = implode(',', $news);
您有一个类似于Users,staff,cinemahall
的字符串.现在,代替检索所有输入,您可能需要一个一个地检索它,因为您需要使news
值发生突变.此外,您还可以使用except()
方法将news
从批量获取所有值中排除.
You have a string which will look like Users,staff,cinemahall
. Now, instead to retrieve all input, you may need to retrieve it one by one, since you need to mutate the news
value. Additionally, you can also use except()
method to exclude news
from mass getting all value.
$news = $request->input('news');
$news = implode(',', $news);
$input = $request->except('news');
//Assign the "mutated" news value to $input
$input['news'] = $news;
General_news::create($input);
return redirect()->back();
这篇关于如何在Laravel 5.2中存储多重选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!