Laravel Form ::选择多个,保存所有选定字段的数组或列表,而不仅仅是最后选择的字段

时间:2015-02-12 01:11:13

标签: php mysql arrays forms laravel-4

嗯,我遇到了一个奇怪的事情,或者到目前为止没有人注意到或者无法从laravel的选择框中保存。

我正在制作类别,这些类别将按类型分隔,但主要问题是我不能使用Form::selectmultiple选项来选择多个类别但是提交laravel保存仅包含最后一个选定字段的字符串,因此,如果laravel仅保存最后一次选择,为什么multiple甚至存在。

这是我的代码示例

{{ Form::select('categories[1]', $platform, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[2]', $developer, null, ['multiple'=>true, 'class' => 'form-control']) }}
{{ Form::select('categories[3]', $publisher, null, ['multiple'=>true, 'class' => 'form-control']) }}

我在我的控制器中定义了$ developer,$ publisher和$ platform,这基本上是特定id下的类别列表。

$platform = Category::->where('type', '=', 1)->lists('name', 'id');

因此,这将返回视图的所有类别的数组。

----------------
| name    | id |
----------------
| Windows |  1 |
----------------
| Linux   |  2 |
----------------
| MacOS   |  3 |
----------------

所以到目前为止这一切都运行良好,在我的网页上,我有一个类别列表,如我想要的选择框中有多个选择

问题是当它被保存时,它只保存选择框中最后一个选定字段的字符串。

提交时我得到了这个

["categories"]=> //This is as expected as i have 3 selects in an array
    array(2) {
      [1]=> // and this is id of first select box and category
          string(1) "3" // and this is the problem, read below please
      [2]=> // and this is id of second select box and category
          string(1) "4"
    }

所以问题就是你可以看到我得到一个数字3的字符串。这个数字实际上代表了最后一个选定字段的id,在这种情况下我选择了id为3的MacOS

我需要得到的是:

["categories"]=>
    array(2) {
      [1]=>
          string(1) "1,3"
      [2]=> 
          string(1) "4"
    }

这意味着我选择WindowsMacOS以后我可以获取该字符串并按该ID分解foreach类别。

["categories"]=>
    array(2) {
      [1]=>
          array(2) {
             [0]=> 1
             [1]=> 3
          }
      [2]=> 
          array(1) {
             [0]=> 4
          }
    }

我能以任何方式使其有效吗?

1 个答案:

答案 0 :(得分:0)

我忘了提到我习惯使用wordpress处理这种工作,用一个查询查询所有数据很容易,它被称为多维数组。

我实际上是通过反复试验弄明白的,我记得在wordpress中使用多维数组时你必须用括号定义每个数组并且它将构成一个树,它在这里是相同的,所以正确的代码将是:

 {{ Form::select('categories[1][]', $platform, null, ['multiple'=>true, 'class' => 'form-control']) }} 
 {{ Form::select('categories[2][]', $developer, null, ['multiple'=>true, 'class' => 'form-control']) }} 
 {{ Form::select('categories[3][]', $publisher, null, ['multiple'=>true, 'class' => 'form-control']) }}

并将它保存在数组中,如下所示:

["categories"]=>
array(2) {
  [1]=>
      array(2) {
         [0]=> 1
         [1]=> 3
      }
  [2]=> 
      array(1) {
         [0]=> 4
      }
}