John Davidson

php - Laravel Eloquent Sync pivot table except specific values

0 comments
Message:


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 class="mb-6">
<label for="package_clients" class="block mb-2 text-sm font-medium flex">Bundle Clients:</label>
<div class="border border-gray-200 rounded-lg">
<div class="p-4 overflow-auto min-h-40 max-h-96">
@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?



My Answer:
php
$package = Package::find($packageId);
$clients = Client::where('permission', 'specific_permission')->get();

$package->clients()->sync($clients->pluck('id')->toArray());

Rate this post

3 of 5 based on 7996 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us