I have a Category
Model which has a parent relation to itself:
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id', 'id');
}
and a ManyToMany relation to FieldCategory
public function fieldcategories()
{
return $this->belongsToMany('App\Models\FieldCategory');
}
And I have a CategoryObserver
to observe if there are any changes of parent (ex. if a category was moved to subcategory) if threre was a change I want to attach parent FielCategory
entries to subcategory
public function updated(Category $category)
{
if($category->parent_id != null) {
$this->updateFieldCategories($category);
}
}
public function updateFieldCategories(Category $category)
{
$category->fieldcategories()->detach();
$parent = \App\Models\Category::find($category->parent->id);
$parentFieldCategoriesArray = [];
foreach ($parent->fieldcategories as $parentCat)
{
$parentFieldCategoriesArray[] = $parentCat->id;
}
$category->fieldcategories()->attach($parentFieldCategoriesArray);
}
And it works fine on updated
! But when I try to do exact thing on created
(when it has parent selected) it fails, and I have no idea why?
I've try to debug this function and $parentFieldCategoriesArray
is filled with necessary ID's. It looks like the $category->fieldcategories()->attach()
method is not firing and I don't know why.
There are no records in the pivot table on created
and on updated
it works fine.
I'm using Laravel 5.6
Any help please?
UPDATE: As requested this is my created function
public function created(Category $category)
{
\Log::debug('PARENT: '.$category->parent_id);
if($category->parent_id != null) {
$this->updateFieldCategories($category);
}
}