Skip to content

Instantly share code, notes, and snippets.

@zetrider
Created May 19, 2020 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zetrider/f431ef12201b5d218b4de5353ba0bf90 to your computer and use it in GitHub Desktop.
Save zetrider/f431ef12201b5d218b4de5353ba0bf90 to your computer and use it in GitHub Desktop.
Sync morphToMany
/**
* Sync morphToMany
*
* @param morphToMany $morphToMany
* @param array $ids
* @return array
*/
public static function syncMorphToMany($morphToMany, $ids)
{
$changes = [
'attached' => [],
'detached' => [],
// 'updated' => [],
];
$morphToMany->get()->each(function ($item) use (&$ids) {
if (in_array($item->id, $ids)) {
unset($ids[array_search($item->id, $ids)]);
} else {
$changes['detached'][] = $item->id;
$item->pivot->delete();
}
});
if (count($ids)) {
$changes['attached'] = $ids;
$morphToMany->attach($ids);
}
return $changes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment