Jamie Jamie - 27 days ago 21
PHP Question

Laravel sync not working with empty array

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?

Answer

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);
    }
}
Comments