6

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);
    }
}
violator667
  • 469
  • 4
  • 19
  • Are you sure the parent is assigned properly to the newly created category? Also, can you show us your created function for your observer? – Chin Leung Aug 14 '18 at 17:45
  • I've updated the question to show you my `created` function. Yes I'm sure the parent is assigned properly. – violator667 Aug 15 '18 at 04:03

2 Answers2

3

I asked this question 1 year ago. See this: Laravel observer for pivot table.

2 options here. Create a custom BelongsToMany or create a custom trait BelongsToManySyncEvents.

Please see my question.

Jamie
  • 10,302
  • 32
  • 103
  • 186
0

Just add:

public $afterCommit = true;

at the beginning of the observer class.. It will wait until the transactions are done, then save your attaching or detaching..

Please check Laravel's documentation for that.

darroosh
  • 751
  • 2
  • 7
  • 18