首页 > 解决方案 > 为 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;
}

标签: laravelvue.jsvuejs2axios

解决方案


感谢哈桑的帮助。问题是 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();
  }
}

现在可以了。


推荐阅读