laravel - 为 foreach() Axios Laravel 提供的参数无效
问题描述
我有一个 Vue.js 表单,我使用 Axios 提交表单。我能够将数据保存到我的数据库中。但是,当我想保存动态添加的输入字段时,我会收到此错误消息...
为 foreach 提供的参数无效
问题是它不是一个数组,但它应该是。如您所见,我想使用 Axios 将 Vue 组件中的 teams[] 数组发送到 Laravel 后端。当我 console.log() 团队 [object object],[object object]。
应用程序.js
new Vue({
el: '#regapp',
data: {
username: '',
email: '',
password: '',
password_confirmation: '',
teams: [
{
name: '',
role: '',
linkedin: '',
profileimg: ''
}
],
methods: {
onSubmit() {
axios.defaults.headers.common["X-CSRF-TOKEN"] = document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content");
let formData = new FormData();
formData.append('username', this.username);
formData.append('email', this.email);
formData.append('password', this.password);
formData.append('password_confirmation', this.password_confirmation);
formData.append('teams', this.teams);
axios.post('register', formData)
.then(response => alert('Success'))
.catch(error => this.errors.record(error.response.data.errors));
}
}
}
});
控制器.php
protected function create(array $data)
{
$user = new User();
$user->name = $data['username'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->save();
// Here I try to loop trough teams and save each of them names into db.
if ($data['teams'][0] != NULL) {
$format = (array)$data;
foreach ($format['teams'] as $teams) { // The error is here
$team = new Team();
$team->user_id = $user->id;
$team->tmembername = $teams->name;
$team->save();
}
}
return $user;
}
解决方案
感谢哈桑的帮助。问题是 this.teams 是一个对象数组——它只是试图将 Object 转换为 String,从而得到 [object Object]。所以我不能这样做:
formData.append('teams', this.teams);
我不得不:
var teammemb = JSON.stringify(this.teams);
然后:
formData.append('teams', teammemb);
在我的 RegisterController.php
$csapat = (json_decode($data['teams']));
if (is_array($csapat) || is_object($csapat)) {
// in this contition, foreach gonna work only array or object exist
foreach ($csapat as $teams) {
$team = new Team();
$team->ico_id = $ico->id;
$team->tmembername = $teams->name;
$team->save();
}
}
现在可以了。
推荐阅读
- sql - 执行排除特定分区名称的 SQL 查询
- javascript - 每次我击中桨画布时添加额外的球对象
- c - 如何在C中计算字符串中字符的频率
- .net - 给定一个 .NET 方法,我们如何知道该方法使用了哪些方法、类型等?
- linux - 一个 openshift-origin 工作节点无法解析 cluster.local 记录,导致 Imagepullbackoff
- javascript - 用户输入后加载 Material UI AutoComplete 建议
- ios - 当崩溃日志包含 _dispatch_call_block_and_release + 24 时会出现什么问题
- react-native - addlistener focus react native 仅适用于第二次刷新 react-native
- java - Java GET HTTP openConnection() 未正确编码 JSON 输出字符串
- amazon-cognito - 如何仅使用 auth 包配置 Amplify?