首页 > 解决方案 > 如何使用 Laravel / Vue JS 修复数组输入值

问题描述

这是一个 Laravel 5 项目。我有一份标准表格正在提交。我正在尝试发送从 vue 组件中添加的搜索功能的结果中单击的每个帐户的 ID。

单击的详细信息随后存储在名为“grantedUsers”的隐藏表单输入中。这具有存储多个值的能力。所以我使用了grantedUsers[]这个名字。

将表单提交到后端后,我已经对值进行了 DD,它显示了所有值,但显示在一个索引中,而不是每个索引的单独索引中。使有效处理数据变得更加困难。

我显然错误地将值提交给隐藏的输入。在将每个 ID 拆分为单独的索引时,我们将不胜感激。

代码

<input type="hidden" name="grantedUsers[]" :value="hiddenData">

//hiddenData is an empty array at initialisation.
data() {
  return {
      keywords: null,
      results: [],
      granted: [],
      hiddenData: []
  };
},

addUser(result) {
   this.granted.push(result);
   this.results.splice(this.results.indexOf(result), 1);

   this.hiddenData.push(result.id);
},

removeUser(grantee) {
   this.results.push(grantee);
   this.granted.splice(this.granted.indexOf(grantee), 1);

   this.hiddenData.splice(this.hiddenData.indexOf(grantee.id), 1);
}
//The backend is outputting this on the DD
array:1 [▼
  0 => "1,2"
]

我正在努力解决

array:2 [▼
  0 => "1"
  1 => "2"
]

标签: laravellaravel-5vue.js

解决方案


[]仅当您有多个具有此名称的输入字段时,添加到输入字段的名称才有用。它不会将单个字段的值转换为数组。

因此,您可以[]从名称中删除 并对字符串执行简单explode操作以使其成为数组。

dd(explode(',', $request->grantedUsers));

推荐阅读