我有一个Vue.js表单,我使用Axios提交表单。我可以将数据保存到我的数据库中。然而,当我想要保存我动态添加的输入域时,我得到了这个错误消息...
为foreach提供的参数无效
问题是它不是一个数组,但它应该是一个数组。正如您所看到的,我想将teams[]数组从Vue组件发送到具有Axios的Laravel后端。当我console.log()组合对象对象时,对象对象。
app.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));
}
}
}
});
Controller.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;
}
发布于 2018-09-04 18:03:06
谢谢Hassan的帮助。问题是this.teams是一个对象数组-它只是试图将对象转换为字符串,从而获得对象对象。所以我不能这样做:
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();
}
}
它现在起作用了。
https://stackoverflow.com/questions/52156946
复制相似问题