How to use toggle column to update pivot table?

I have a many-to-many relationship with product, user, and product_user_fav models, and I want to create a favorite toggle column in the products table to update the product_user_fav table (pivot).

That is when a user switches the favorite toggle column in the products table if there are no user_id and product_id rows in the Product_user_fav table, a new row is registered in the pivot table, and if there are user_id and product_id, the existing row is removed.

How can I do this? Thank you!

#user model
id, name

#product model
id, name

....
  public function users()
    {
        return $this->belongsToMany(User::class, 'product_user_fav');
    }

#product_user_fav model
user_id, product_id

#produts table
   public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('title')
                    ->label('Name'),
                Tables\Columns\ToggleColumn::make('?')
                    ->label('Fav'),
            ])
            ->filters([
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->recordUrl(null);
    }
image.png
Was this page helpful?