Harshana Nishshanka
Harshana Nishshanka

Reputation: 45

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

Upvotes: 1

Views: 1575

Answers (2)

Harshana Nishshanka
Harshana Nishshanka

Reputation: 45

Finally I found the solution thanks to Kevin

public static function boot()
{
    parent::boot();

    static::deleting(function ($category) {
        $products = $category->products;

        if ($products->isNotEmpty()) {
            $category->products()->detach();
            $defaultCategory = static::find(1);
            $defaultCategory->products()->sync($products->pluck('id')->toArray());
        }
        
    });
}

Upvotes: 2

Kevin Bui
Kevin Bui

Reputation: 3035

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

Upvotes: 0

Related Questions