PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] Laravel observer not attaching on pivot table

 March 11, 2022     laravel, laravel-5.6     No comments   

Issue

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);
    }
}

Solution

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.



Answered By - Jamie
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing