I've a method looks like this:
public function saveContacts(Request $request)
{
if($request->contacts) {
$contacts = collect($request->contacts)->pluck('id');
$this->contacts()->sync($contacts->toArray());
}
}
It's working but if $request->contacts
is an empty array it does not remove all records. What could be the case here?
You can do this:
if ($request->contacts) {
$contacts = collect($request->contacts)->pluck('id')->toArray();
if (empty($contacts)) {
$this->contacts()->detach();
} else {
$this->contacts()->sync($contacts);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With