0

I want to loop through the array and insert them into the database. When i check dd($request->users), it displays "NULL" but if i put dd($request->all()), the data array appears. Plus the code for controller below doesn't insert the data into the database. Thanks

Script

<script>
export default {
    data(){
      return{  
            users: [{
                username:'',
                password:'',
                phone:'',
                email:''
            }]
      }
    },
    methods:{
        addMoreData(){
            this.users.push({
                username: '', 
                password: '' , 
                email: '',
                phone:''
                });
        },
        deleteData(index){
            this.users.splice(index,1)  
        },
        submitData(){
         axios.post('/api/user', this.users)
      }
    },
    mounted() {
        console.log('Component mounted.')
    }
}

Controller

    public function store(Request $request)
{   
    for ($i = 1; $i < count($request->all()); $i++) {
        data::create([
                'username'=>$request->username[$i],
                'password'=>$request->password[$i],
                'phone'=>$request->phone[$i],
                'email'=>$request->email[$i]
            ]);
    }
}

Edited

Result for dd(request->all()

Result for dd(request->users

2
  • First you need to variable for creating user. Like $user = User::create([..]). Can you write dd($request->all()) and display result here? Commented Jun 2, 2019 at 9:14
  • @mare96 check the edit Commented Jun 2, 2019 at 9:22

2 Answers 2

1

This should work in your case i think.

public function store(Request $request)
{ 
   foreach($request->all() as $user){
      $u = User::create([
             'username'=>$user['username'],
             'password'=>$user['password'],
             'phone'=>$user['phone'],
             'email'=>$user['email']
      ])
     return ...
   }
}

But if you want to send users from frontend you will need to place users in new array named users. Good luck.

Sign up to request clarification or add additional context in comments.

1 Comment

i got this error "message: "Trying to get property 'username' of non-object "
0

If your data in this format as per your this image

enter image description here

In controller:

public function store(Request $request){   

    $users = $request->all();

    if(!empty($users)){
        foreach($users as $user){
           data::create($user);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.