Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Has Many Sync Laravel Package

korridor/laravel-has-many-sync

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require korridor/laravel-has-many-sync
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Korridor\HasManySync\HasManySyncServiceProvider"
    
  2. First Use Case: Add the trait to your model:

    use Korridor\HasManySync\HasManySync;
    
    class Post extends Model
    {
        use HasManySync;
    
        public function tags()
        {
            return $this->hasMany(Tag::class);
        }
    }
    

    Now use syncHasMany() instead of sync():

    $post = Post::find(1);
    $post->syncHasMany('tags', [1, 2, 3]); // Syncs tags with IDs 1, 2, 3
    
  3. Key Files:

    • config/has-many-sync.php (for customization)
    • app/Models/YourModel.php (where you apply the trait)

Implementation Patterns

Core Workflows

  1. Basic Syncing:

    // Sync by IDs
    $model->syncHasMany('relation', [1, 2, 3]);
    
    // Sync by full models
    $model->syncHasMany('relation', Tag::find([1, 2, 3]));
    
  2. Bulk Operations:

    // Sync for multiple models
    Post::where('category', 'news')->get()->each(function ($post) {
        $post->syncHasMany('tags', [1, 4, 5]);
    });
    
  3. Conditional Syncing:

    if ($request->has('new_tags')) {
        $post->syncHasMany('tags', $request->input('new_tags'));
    }
    
  4. Integration with Eloquent Events:

    // Listen for sync events
    $model->syncHasMany('relation', $data, function ($model, $relation, $data) {
        // Custom logic before sync
    });
    
  5. Customizing Behavior:

    // Override default behavior in model
    public function syncHasMany($relation, $data, $detaching = true, $touch = true)
    {
        // Custom logic
        parent::syncHasMany($relation, $data, $detaching, $touch);
    }
    

Common Patterns

  • API Controllers:

    public function update(Request $request, Post $post)
    {
        $post->syncHasMany('tags', $request->tags);
        return $post;
    }
    
  • Form Requests:

    public function rules()
    {
        return [
            'tags' => 'sometimes|array',
        ];
    }
    
  • Seeding:

    $post = Post::factory()->create();
    $post->syncHasMany('tags', Tag::factory()->count(3)->create()->pluck('id'));
    

Gotchas and Tips

Pitfalls

  1. Namespace Mismatch:

    • Version 1.* uses Korridor\HasManyMerged\HasManySync, while 2.* uses Korridor\HasManySync\HasManySync.
    • Fix: Ensure you’re using the correct use statement based on your installed version.
  2. Missing Relation:

    • If the relation method doesn’t exist, the package will throw an error.
    • Fix: Define the relation method (e.g., hasMany, belongsToMany) before using syncHasMany.
  3. Detaching Behavior:

    • By default, detaching = true removes all non-specified records. Set to false to avoid detaching:
      $model->syncHasMany('relation', $data, detaching: false);
      
  4. Touching Timestamps:

    • The touch parameter (default: true) updates the parent model’s updated_at. Disable with:
      $model->syncHasMany('relation', $data, touch: false);
      
  5. Performance with Large Datasets:

    • Syncing thousands of records may cause timeouts or memory issues.
    • Fix: Use chunking or queue the sync job:
      SyncHasManyJob::dispatch($model, 'relation', $data)->onQueue('sync');
      

Debugging Tips

  1. Check Sync Events:

    • Enable query logging to debug SQL:
      DB::enableQueryLog();
      $model->syncHasMany('relation', $data);
      dd(DB::getQueryLog());
      
  2. Validate Input:

    • Ensure $data is an array of IDs or models. Invalid input may cause silent failures.
  3. Model Events:

    • Override syncHasMany in your model to add logging or validation:
      public function syncHasMany($relation, $data, $detaching = true, $touch = true)
      {
          $this->validateSyncData($relation, $data);
          parent::syncHasMany($relation, $data, $detaching, $touch);
      }
      

Extension Points

  1. Custom Sync Logic:

    • Extend the trait or create a macro:
      Model::macro('syncHasManyCustom', function ($relation, $data) {
          // Custom logic
          $this->syncHasMany($relation, $data);
      });
      
  2. Queueable Sync:

    • Create a job for async syncing:
      class SyncHasManyJob implements ShouldQueue
      {
          use Dispatchable, InteractsWithQueue, Queueable;
      
          public function handle()
          {
              $this->model->syncHasMany($this->relation, $this->data);
          }
      }
      
  3. Custom Validation:

    • Add validation rules in the model:
      protected function validateSyncData($relation, $data)
      {
          if (!is_array($data)) {
              throw new \InvalidArgumentException('Data must be an array.');
          }
      }
      
  4. Config Overrides:

    • Customize behavior via config/has-many-sync.php:
      'default_detaching' => false,
      'default_touch' => false,
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui