Search code examples
phplaravelone-to-manyeloquent-relationship

Laravel safest way to delete a many to many relationship data while sync (replace) with another


I have a project with Product, Category relationship which is Many to Many

// Product Model
public function categories()
{
   return $this->belongsToMany(Category::class);
}

//Category Model
public function products()
{
   return $this->belongsToMany(Product::class);
}

Now, when a some category gets deleted, I want to assign it's products to a default category (ID = 1). What is the best way to achieve this with Laravel 8


Solution

  • You might want to try the deleting event:

    class Category extends Model
    {
        public static function booted()
        {
            static::deleting(function ($category) {
                $products = $category->products()->get();
    
                if ($products->isNotEmpty()) {
                    $category->products()->detach();
                    $defaultCategory = static::find(1);
                    $defaultCategory->products()->sync($products->pluck('id')->toArray());
                }
                
            })
        }
    }