首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为foreach() Axios Laravel提供的参数无效

为foreach() Axios Laravel提供的参数无效
EN

Stack Overflow用户
提问于 2018-09-04 07:03:42
回答 1查看 851关注 0票数 0

我有一个Vue.js表单,我使用Axios提交表单。我可以将数据保存到我的数据库中。然而,当我想要保存我动态添加的输入域时,我得到了这个错误消息...

为foreach提供的参数无效

问题是它不是一个数组,但它应该是一个数组。正如您所看到的,我想将teams[]数组从Vue组件发送到具有Axios的Laravel后端。当我console.log()组合对象对象时,对象对象。

app.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2018-09-04 18:03:06

谢谢Hassan的帮助。问题是this.teams是一个对象数组-它只是试图将对象转换为字符串,从而获得对象对象。所以我不能这样做:

代码语言:javascript
复制
formData.append('teams', this.teams);

我不得不:

代码语言:javascript
复制
var teammemb = JSON.stringify(this.teams);

然后:

代码语言:javascript
复制
formData.append('teams', teammemb);

在我的RegisterController.php

代码语言:javascript
复制
 $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();
  }
}

它现在起作用了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52156946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档