0

Here is my code:

public function updateGroupIntoDatabase(){

    $group_id = 6;
    $group = Group::find($group_id);
    $group -> name = Input::get('groups');
    $projectsIds = Input::get('projects');

    $userIds = array_merge(Input::get('clients'),Input::get('workers'));
    array_push($userIds, Auth::id());
    $adminId = Auth::id();
    if($group -> save()){
    foreach($userIds as $userId){

       $name = User::find($userId);

       $group -> projects() -> sync($projectsIds,array('admin_id' => $adminId, 'user_id' => $userId,'user_name' => $name -> name));

    }

when I execute this I get like this:

id  project_id  group_id admin_id user_id  user_name
1   4           6        0        0

But it should for each user_id create new record... When I use attach method It works find but when I use sync it create just one record with additional pivot fields filds 0. Any solution for this?

Vladimir Djukic
  • 2,042
  • 7
  • 29
  • 60

1 Answers1

1

When using sync with pivot data:

$group->projects()->sync( array( 
    1 => array( 'admin_id' => $adminId, 'user_id' => $userId ),
    2 => array( 'admin_id' => $adminId, 'user_id' => $userId ),
    ...
));
rozklad
  • 442
  • 6
  • 11
  • How can I insert it into my `foreach` loop? – Vladimir Djukic Jul 08 '15 at 13:05
  • i assume your projectIds is array of ints, so before you do sync, add loop like `$sync_array = array(); foreach( $projectsIds as $project_id) { $sync_array[$project_id] = array( 'admin_id' => $adminId, 'user_id' => $userId ); }` and then change your sync to `$group -> projects() -> sync($sync_array)` – rozklad Jul 08 '15 at 13:19
  • It retrun array like this `array:2 [ 1 => array:2 [ "admin_id" => 1 "user_id" => 1 ] 2 => array:2 [ "admin_id" => 1 "user_id" => 1 ]]` but `user_id` not changed.... – Vladimir Djukic Jul 08 '15 at 13:48