I want to use sync()
for table client_package
except some values/fields.
It's because I'm displaying checkboxes
with client
names, that I want to add to a package
.
So if User has specific permission
, he could see specific clients
, and it's done:
<div >
<label for="package_clients" >Bundle Clients:</label>
<div >
<div >
@foreach($clients as $client)
<p><input type="checkbox" name="package_clients[]" id="client-{{$client->id}}" value="{{ $client->id }}"
@foreach($package_clients as $package_client)
@if($client->id == $package_client->id) checked @else @endif
@endforeach
/>
<label for="bundle-{{$client->id}}"> {{ $client->name }} </label>
</p>
@endforeach
</div>
</div>
</div>
But after syncing
the list of clients
assigned to a package
I got detached
clients, that are not in the list (the remaining ones from the DataBase).
I want to avoid that, but in my case I can't use attach()
and detach()
separately(depending on situation), because User could assign and misallocate multiple clients
at once.
I want to pass f.e. array
of Clients, that could not be detached
. Is that possible?
My way to syncing Clients to Package:
$package->clients()->sync($clients);
$clients
is an array of id's
.
Or there's a option of doing the sync()
only on that Collection of clients
not in whole DB?
CodePudding user response:
How about use syncWithoutDetaching()
instead of sync()
?
Edited :
How about using the wherePivotNotIn()
example :
$package->clients()->wherePivotNotIn('client_id', $clients)->sync($clients);
CodePudding user response:
// it's your array of client's ids
$client_ids = $request->package_clients;
// it's ur clients
$clients = Client::whereIn('id',$client_ids)->get();
// and sync. that's all
$package->clients()->sync($clients);