Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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