Laravel Sync method sends only 2nd data

This piece of code should remove all old data from the database and add new ones (using sync ())

Now I have a project with users, and the user can be associated with the project using the checkbox.

Thus, the checkbox is checked, this function will be launched, but, for example, when I say that user 1they user 2go through this fuction to add it to it pivot table, it will send only user 2and user 1it will not go, what’s wrong?

And when I add 3 user user 1, user 2, user 3, it will be added only user 2.

controller

public function update(CreateProjectRequest $request)
{
    if($request->get('contribute'))
    {
        foreach($request->get('contribute') as $k => $contribute)
        {
            if($contribute == 1)
            {
                $project = $this->project->find($request->project_id);
                $project->users()->sync(array($k));

            }
        }
    }

    $project = $this->project->find($request->project_id);
    $project->fill($request->input())->save();

    return redirect('project');
}

Blade

@foreach($users as $user)
            <tr>
                <td>
                    {{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
                </td>
                <td>
                    {!! Form::checkbox('contribute['.$user->id.']', '1', $user->projects->contains('id', $project->id)) !!}
                </td>
            </tr>
@endforeach

At a dd($request->input());at the beginning of my upgrade method (with a selection of at least 3 users) this will return:

  array:9 [▼
  "_method" => "PATCH"
  "_token" => "0uIZNn6zwZjVKfgE0ckhDULeYda0OaLzKVdUgoM8"
  "name" => "Dire Straits"
  "completion_date" => "2015-05-18"
  "DataTables_Table_0_length" => "10"
  "contribute" => array:3 [▼
    1 => "1"
    3 => "1"
    2 => "1"
  ]
  "completed" => "1"
  "active" => "0"
  "project_id" => "11"
]

, 1 / 3 / 2 user_id => 1 .

+4
1

, sync loop 3 , , . sync ex:

$project->users()->sync([1,3,2]);

, , attach, contribute==1 detach, contribute==0

, contribute , , , :

$this->project->users()->sync(array_keys($request->get('contribute'));

, , , .

$project = $this->project->find($request->project_id);
+2

Source: https://habr.com/ru/post/1589037/


All Articles