[英]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. 它正在工作,但如果$request->contacts
是一个空数组,它不会删除所有记录。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.