Reputation: 1402
My view has a multiple select box for which allows a user to be assigned certain assets. Users are pulled from table users
, assets are pulled from table assets
.
<div class="form-group">
<label for="assets" class="col-sm-5 control-label">Assets </label>
<div class="col-sm-6">
{{Form::select('assets[]',$user->assets, $user->takenAssets, ['id'=>'assets','multiple','class'=>'select2 form-control'])}}
</div>
</div>
In the select box above, $user->assets
lists an array taken from the model Asset::all('name','id')
, taken assets are simply $user->assets->pluck('id')->toArray();
. These are done to populate the box and then list the selected ones.
There are five text fields below this multiple select box which allow a user to enter optional serial numbers, each text box as a name field called serialnumber[]
Now once the controller receives the request, the following code runs:
if(!collect($request->assets)->isEmpty())
{
for($i = 0; $i<count($request->assets);$i++)
{
$user->assets()->sync([$i+1 => array('serialnumber'=>$request->serialnumber[$i])]);
}
}
The $i+1
happening in the for loop is because of the way the id
s in the assets
tables start with 1.
It's not updating the asset_user
table. What's going wrong?
Upvotes: 0
Views: 3285
Reputation: 652
The method sync takes as parameter an array of IDs to synchronize and will dettach all of the others. That mean if you sync your IDs one by one, the first ID will be dettached when you will sync the second, the second will be dettached by the third...
If $request->assets is an array of IDs, why do you not simply do something like :
if($request->has('assets')) {
$user->assets()->sync($request->assets);
}
Upvotes: 2