I have a table that holds the 'Officiant_id'
and 'awards_id'
When a user edits their profile it will display in a checkbox all the available ones and auto check the ones that are on that table.
Although, now its time to update, let's say a user unselects one, how can I update the table to delete it, or if they check a new one add that new one to the table.
@if(!empty($officiant - > useraward))
@foreach($officiant - > useraward as $arr)
@php $removeId[] = $arr - > id @endphp {
{
Form::checkbox('awards[]', $arr - > id, true, ['class' => ''])
}
} {
{
$arr - > name
}
} {
!!'<br>'!!
}
@endforeach
@endif
@php
$offaward = Info::officiantAwards();
foreach($removeId as $key) {
unset($offaward[$key]);
}
@endphp
@foreach($offaward as $k => $v) {
{
Form::checkbox('awards[]', $k, false)
}
} {
{
$v
}
} {
!!'<br>'!!
}
@endforeach
if (!empty($request - > awards)) {
foreach($request - > awards as $i => $k) {
$awards[] = $request - > $k;
}
}
Get all awards as an array and call the sync()
method on your $officiant
.According to documentation/Syncing Associations
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:
So in your case after calling the update()
or save()
,
//get all award ids
$awards = $request->get('awards');
//save or update officient action
//updating relation
$officiant->awards()->sync($awards);