Created
May 19, 2020 19:55
-
-
Save zetrider/f431ef12201b5d218b4de5353ba0bf90 to your computer and use it in GitHub Desktop.
Sync morphToMany
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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