Reputation: 1212
This piece of code should be deleting all old data from the database and when add the new ones (using sync())
Now I have a project with users, and a user can be linked to a project with a checkbox.
So on checkbox checked this function will trigger, but for example when I say that user 1
and user 2
are going through this fuction to get added to the pivot table
it will only send user 2
, and user 1
will not get through, what is going wrong?
And when I add 3 users user 1
, user 2
, user 3
, only user 2
will get added.
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
On a dd($request->input());
at the start of my update method (with selecting atleast 3 users) this will get in 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"
]
So 1 / 3 / 2
would be the user_id
and => 1
should be the value.
Upvotes: 4
Views: 1497
Reputation: 2731
The problem is that sync
gets called in loop
3 times so each time it's syncing one value. You have to pass an array of the ids in sync
ex:
$project->users()->sync([1,3,2]);
Or if you want you can use attach
when contribute==1
and detach
when contribute==0
Or if contribute
doesnt return input when a user is deselected and it only returns when it is selected then you can try:
$this->project->users()->sync(array_keys($request->get('contribute'));
I just noticed that you have another bug unless you are updating many projects with one call you should put the line below on the first line of your function.
$project = $this->project->find($request->project_id);
Upvotes: 2