Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel sync not working with empty array

Tags:

php

laravel

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?

like image 292
Jamie Avatar asked Nov 08 '16 14:11

Jamie


1 Answers

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);
    }
}
like image 165
Alexey Mezenin Avatar answered Oct 11 '22 06:10

Alexey Mezenin