关于vue.js:为foreach()提供了无效的参数Axios Laravel

Invalid argument Supplied for foreach() Axios Laravel

我有一个Vue.js表单,我使用Axios提交了表单。 我可以将数据保存到数据库中。 但是,当我要保存动态添加的输入字段时,会收到此错误消息...

Invalid argument supplied for foreach

问题在于它不是数组,而应该是数组。 如您所见,我想使用Axios将Vue组件的teams []数组发送到Laravel后端。 当我console.log()团队[对象对象],[对象对象]时。

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}


感谢Hassan的帮助。
问题是this.teams是一个对象数组-它只是尝试将Object转换为String,因此得到[object Object]。
所以我不能这样做:

1
formData.append('teams', this.teams);

我不得不:

1
var teammemb = JSON.stringify(this.teams);

然后:

1
formData.append('teams', teammemb);

在我的RegisterController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
 $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();
  }
}

现在可以使用了。