简体   繁体   中英

Array to string conversion in laravel 5.4 , controllers

I'm getting array to conversion error while inserting multiple data , code which i mentioned below please take a look and somebody help me

Controller.php

         if(!empty($value))
                {
                    foreach ($value as $v) 
                    {   
                        $insert[] = ['name' => $v['name'], 'email' => $v['email'],'company_name' => $v['company_name'],'company_id' => $v['company_id'], 'emp_id' => $v['emp_id']];     
                         $role_id= $v['role_id'];
                         $name=$v['name'];
                         $email=$v['email'];
                         $emails[]=$v['email'];
                         $emp_id=$v['emp_id'];                      
                         $data = array( 'name' => $name,'email' => $email , 'emp_id' => $emp_id);
                         $roles[]= $v['role_id']; 

                    }
                }
            }

            if(!empty($insert))
            {
                 $inserted=User::insert($insert);
                 if($inserted)
                 {
                     $email_select=User::select('id')->whereIn('email',$emails)->where('company_id',Auth::user()->company_id)->orderBy('id','Asc')->get();
                    foreach ($email_select as $key => $idget) 
                    {
                        $getid[]=$idget->id;
                    }
                 }
                 $datas[]=['user_id' => $getid , 'role_id' => $roles];                  
                 $insert_role=DB::table('role_user')->insert($datas) ;

I'm getting error called array to string conversion while insert_role variable execution

(2/2) QueryException Array to string conversion (SQL: insert into role_user ( role_id , user_id ) values (1, 16))

Make $roles[]= $v['role_id']; to $roles= $v['role_id'];

And $getid[]=$idget->id; to $getid=$idget->id;

$roles and $getid are both arrays. I am guessing you want to assign all roles to all selected mail addresses. Then you would have to do the following:

if($inserted)
{
    $email_select=User::select('id')->whereIn('email',$emails)->where('company_id',Auth::user()->company_id)->orderBy('id','Asc')->get();
    foreach ($email_select as $key => $idget) 
    {
        foreach($roles as $role) {
            $datas[] = ['user_id' => $idget->id, 'role_id' => $role];
        }
    }
}
$insert_role=DB::table('role_user')->insert($datas);

I think this should work.

instead of assigning in array, you are trying to assign as string, that is what causing you the error, possible fix is.

$roles[]= $v['role_id']; 
$getid[]=$idget->id;  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM