Norbertho
131
12
Laravel

Invalid argument supplied for foreach()

Posted 6 months ago by Norbertho

Hi, I have vue form and i submitting the form with axios. I can manage to save data to my database but when i want to save my dynamically added input fields i have this error message Invalid argument supplied for foreach() Basically the user when register can add team members as well dynamically and whene i save the user to the database i would like to save team members name as well.

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));

  },

RegisterController.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) {    <--- this line gives the error
            $team = new Team();



            $team->user_id = $user->id;
            $team->tmembername = $teams->name;

            $team->save();
        }
}
return $user;

    }

}

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.