I'm trying to insert/delete related categories to a resource. The view generates a list with checkboxes all named 'category[]', the value/title are from a domain table resource_category_list
Models: Resource has many ResourceCategory (alias category) ResourceCategory belongsto Resource and ResourceCategoryList ResourceCategoryList has many ResourceCategory
This is what I came up with:
$resource = Resource::findFirst($resource_id);
$category_selected = array_map(function ($item) { return $item['resource_category_list_id']; }, $resource->getCategory()->toArray())?:[];
if($this->request->isPost())
{
$category_selected_post = $this->request->getPost('category')?:[];
$category_add = array_diff($category_selected_post, $category_selected);
$category_remove = array_diff($category_selected, $category_selected_post);
foreach ($category_add as $resource_category_list_id) {
$cat = new ResourceCategory();
$cat->resource_id = $resource->id;
$cat->resource_category_list_id = $resource_category_list_id;
$cat->save();
}
$resource->category->delete(function($cat) use($category_remove) { return in_array($cat->resource_category_list_id, $category_remove); });
$category_selected = $category_selected_post;
}
I'm wondering if there is a better way to achieve te same result? Without completely deleting and reassinging categories to the resource.