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 Duplicate Laravel Package

neurony/laravel-duplicate

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require neurony/laravel-duplicate
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Neurony\Duplicate\DuplicateServiceProvider"
    
  2. Basic Usage:

    use Neurony\Duplicate\Facades\Duplicate;
    
    $original = App\Models\Post::find(1);
    $duplicate = Duplicate::duplicate($original);
    
  3. First Use Case: Clone a Post with its comments (hasMany) and author (belongsTo):

    $post = App\Models\Post::find(1);
    $clonedPost = Duplicate::duplicate($post, [
        'comments' => true, // Duplicate related comments
        'author' => false,  // Skip duplicating author (avoid circular refs)
    ]);
    

Where to Look First

  • README.md: Focus on the Usage and Customisations sections.
  • Config File: Check config/duplicate.php for default behaviors (e.g., excluded fields, relationship handling).
  • Events: Review the Events section for hooks like duplicating or duplicated.

Implementation Patterns

Core Workflows

  1. Basic Duplication:

    $duplicate = Duplicate::duplicate($model);
    
    • Automatically handles hasOne, hasMany, belongsTo, and belongsToMany relationships.
    • Skips morph* relationships by default (configure via config/duplicate.php).
  2. Selective Relationship Duplication:

    $duplicate = Duplicate::duplicate($model, [
        'relationships' => ['comments', 'tags'], // Only duplicate these
        'exclude' => ['deleted_at'],             // Skip soft-deletes
    ]);
    
  3. Custom Field Handling:

    Duplicate::duplicate($model, [
        'custom' => [
            'slug' => function ($originalSlug) {
                return "copy-of-{$originalSlug}";
            },
        ],
    ]);
    
  4. Batch Duplication:

    $ids = [1, 2, 3];
    Duplicate::duplicateMany(App\Models\Post::find($ids), [
        'relationships' => ['comments'],
    ]);
    

Integration Tips

  • Service Layer: Encapsulate duplication logic in a service class to centralize configurations:

    class PostDuplicator {
        public function duplicateWithAssets(Post $post) {
            return Duplicate::duplicate($post, [
                'relationships' => ['comments', 'attachments'],
                'custom' => ['slug' => fn($s) => "copy-{$s}"],
            ]);
        }
    }
    
  • Admin Panels: Useful for "Clone" buttons in backends (e.g., Nova, Filament). Example for Filament:

    use Neurony\Duplicate\Facades\Duplicate;
    
    public function duplicate(Post $record) {
        return Duplicate::duplicate($record);
    }
    
  • Seeding: Duplicate seed data with relationships:

    $originalUser = User::factory()->create();
    $duplicateUser = Duplicate::duplicate($originalUser, [
        'relationships' => ['posts', 'roles'],
    ]);
    
  • Testing: Reset duplicated models in tests:

    public function tearDown(): void {
        Duplicate::duplicateMany(User::all())->each->delete();
        parent::tearDown();
    }
    

Gotchas and Tips

Pitfalls

  1. Circular References:

    • Duplicating a User with a belongsTo Company and vice versa causes infinite loops.
    • Fix: Explicitly exclude one side:
      Duplicate::duplicate($user, ['exclude_relationships' => ['company']]);
      
  2. Polymorphic Relationships:

    • morph* relationships are skipped by default. Enable with:
      'config/duplicate.php':
      'morph_relationships' => true,
      
  3. Auto-Increment IDs:

    • Duplicated models retain original IDs unless you reset them:
      Duplicate::duplicate($model)->fresh()->setAttribute('id', null)->save();
      
  4. Timestamps:

    • Duplicates inherit original timestamps. Override in custom:
      'custom' => [
          'created_at' => now(),
          'updated_at' => now(),
      ],
      
  5. Soft Deletes:

    • Soft-deleted models are duplicated but remain "deleted." Force deletion:
      Duplicate::duplicate($model)->forceDelete();
      
  6. Event Conflicts:

    • If duplicating or duplicated events trigger side effects (e.g., notifications), disable them:
      Duplicate::duplicate($model, ['events' => false]);
      

Debugging

  • Log Duplication: Enable debug mode in config/duplicate.php:

    'debug' => env('DUPLICATE_DEBUG', false),
    

    Logs appear in storage/logs/laravel.log.

  • Check Relationships: Verify relationships are loaded before duplication:

    $model->load(['comments', 'author']); // Ensure eager-loaded
    
  • Validate Config: Test with a minimal model first:

    $simpleModel = new class extends Model {};
    Duplicate::duplicate($simpleModel); // Confirm no errors
    

Extension Points

  1. Custom Duplicator: Extend the core logic by binding your own duplicator:

    Duplicate::extend(function ($duplicator) {
        $duplicator->afterDuplicate(function ($original, $duplicate) {
            // Post-duplication logic (e.g., log, notify)
        });
    });
    
  2. Override Defaults: Modify the config file to change global behavior (e.g., default excluded fields):

    'exclude' => [
        'id',
        'uuid',
        'deleted_at',
        'created_at',
        'updated_at',
    ],
    
  3. Add New Relationship Types: If using custom relationship types, patch the duplicator:

    Duplicate::extend(function ($duplicator) {
        $duplicator->addRelationshipHandler('customMany', function ($original, $duplicate, $relationship) {
            // Custom logic for 'customMany' relationships
        });
    });
    
  4. Hook into Events: Listen for duplication events to add pre/post-processing:

    event(new Duplicating($original, $duplicate));
    event(new Duplicated($original, $duplicate));
    

Performance Tips

  • Batch Relationship Loading: Load relationships in chunks for large datasets:

    $model->loadMissing(['comments' => function ($query) {
        $query->limit(100);
    }]);
    
  • Disable Events for Bulk: Skip events during batch operations:

    Duplicate::duplicateMany($models, ['events' => false]);
    
  • Queue Duplication: Offload heavy duplication to queues:

    Duplicate::duplicate($model)->onQueue('duplicates');
    
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle