如何在 Laravel 5.2 中存储多个 select 值

How to store multi select values in Laravel 5.2

我有一个存储新闻的表单。

这里我使用的是 Multiselect,我想将 table 中的所有选定选项保存为字符串,例如 Users,staff,cinemahall。

我的控制器存储值的功能是

 public function store(Request $request)
{

    $input=$request->all();

    General_news::create($input);
    return redirect()->back();
}

此函数存储所有提交的字段,但对于多选,它仅存储最后一个选项,即 cinemahall

提交表单时会显示所有选定的选项,但它没有正确保存在数据库中 table。

帮我解决这个问题。

确保将名称属性设置为数组

<select multiple="multiple" name="news[]" id="news">

将其存储为以逗号分隔的字符串

$news = $request->input('news');
$news = implode(',', $news);

你有一个看起来像 Users,staff,cinemahall 的字符串。现在,要检索所有输入,您可能需要一个一个地检索它,因为您需要改变 news 值。此外,您还可以使用 except() 方法从质量获取所有值中排除 news

$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();

如果您使用多选,这可能意味着您需要多对多关系和一个枢轴 table。有点像 posts 可以属于许多 tagstags 可以属于许多 posts

在您的情况下,这可能介于 newsnews_types table 之间。

谢谢@Chay22

您还可以使用 Mutators 和 Accessor https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

public function setFooAttribute($value)
{
    $this->attributes['foo'] = implode(',',$value);
}

public function getFooAttribute($value)
{
    return explode(',',$value);
}