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

Db Archive Laravel Package

ringlesoft/db-archive

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require ringlesoft/db-archive
    php artisan vendor:publish --provider="RingleSoft\DbArchive\DbArchiveServiceProvider" --tag="config"
    
  2. Configure config/db-archive.php:
    'connection' => 'mysql', // Your DB connection
    'default_archive_table_suffix' => '_archive', // Suffix for archived tables
    'archive_retention_days' => 30, // Default retention period
    
  3. First Use Case: Archive old records from a posts table (older than 30 days):
    use RingleSoft\DbArchive\Facades\DbArchive;
    
    DbArchive::archive('posts', now()->subDays(30));
    

Key Files to Review

  • config/db-archive.php (Configuration)
  • app/Console/Kernel.php (Scheduling jobs)
  • app/Models/ (Model-specific archiving logic)

Implementation Patterns

Core Workflows

1. Basic Archiving

// Archive records older than 30 days in the 'orders' table
DbArchive::archive('orders', now()->subDays(30));
  • Automatically creates orders_archive table (if configured).
  • Moves records to the archive while preserving foreign keys.

2. Model-Based Archiving

Extend RingleSoft\DbArchive\Archivable trait in your model:

use RingleSoft\DbArchive\Archivable;

class Post extends Model
{
    use Archivable;

    protected $archiveRetentionDays = 90; // Override default
}

Then archive via:

Post::archiveOldRecords();

3. Scheduled Jobs

Add to app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
    $schedule->command('db-archive:run')->dailyAt('2:00');
}

Run via:

php artisan db-archive:run

4. Custom Archive Tables

Specify a custom suffix or table name:

DbArchive::archive('users', now()->subYear(), [
    'archive_table' => 'user_history',
]);

5. Soft Archiving (Preserve Original Table)

Use softArchive to mark records as archived (instead of moving them):

DbArchive::softArchive('comments', now()->subDays(60));

Integration Tips

  • Foreign Keys: Ensure archived tables include foreign key constraints if needed.
  • Indexes: Rebuild indexes on archive tables post-migration for performance.
  • Transactions: Wrap archiving in transactions for critical tables:
    DB::transaction(function () {
        DbArchive::archive('transactions', now()->subMonth());
    });
    
  • Testing: Use DbArchive::fake() in tests to mock archiving:
    DbArchive::fake()->shouldArchive('posts', now()->subDays(30));
    

Gotchas and Tips

Pitfalls

  1. Foreign Key Conflicts:

    • If archived tables reference other archived tables, ensure constraints are updated or disabled during migration.
    • Fix: Use DbArchive::archive() with skipForeignKeys: true (if supported).
  2. Large Tables:

    • Archiving tables with millions of rows may time out or lock the table.
    • Fix: Batch operations using chunk():
      DB::table('logs')->where('created_at', '<', now()->subYear())
          ->chunk(1000, function ($records) {
              DbArchive::archiveRecords($records, 'logs_archive');
          });
      
  3. Configuration Overrides:

    • Model-specific retention days ($archiveRetentionDays) override global config.
    • Tip: Document overrides clearly in model docblocks.
  4. Soft Deletes:

    • Soft-deleted models (SoftDeletes) may not archive correctly if deleted_at is not considered.
    • Fix: Explicitly filter soft-deleted records:
      DbArchive::archive('posts', now()->subDays(30), [
          'where' => function ($query) {
              $query->whereNull('deleted_at');
          },
      ]);
      
  5. Downtime:

    • Archiving large tables may cause downtime. Schedule during low-traffic periods.

Debugging

  • Log Archiving: Enable debug mode in config:

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

    Logs will appear in storage/logs/laravel.log.

  • Dry Runs: Use --dry-run flag in Artisan:

    php artisan db-archive:run --dry-run
    

    This simulates archiving without executing migrations.

  • Table Existence: If archiving fails with "table doesn't exist," manually create the archive table:

    php artisan db-archive:create-archive-table posts
    

Extension Points

  1. Custom Archive Logic: Override the archiving process by binding your own archiver:

    $archiver = app()->make(\RingleSoft\DbArchive\Contracts\Archiver::class);
    $archiver->archive($table, $cutoff, $options);
    
  2. Pre/Post Archive Hooks: Publish and extend the package's views or listeners:

    php artisan vendor:publish --provider="RingleSoft\DbArchive\DbArchiveServiceProvider" --tag="views"
    
  3. Custom Archive Columns: Add computed columns (e.g., archived_at) to archive tables by extending the ArchiveBuilder:

    // In a service provider
    $this->app->bind(\RingleSoft\DbArchive\Contracts\ArchiveBuilder::class, function () {
        return new CustomArchiveBuilder();
    });
    
  4. Backup Strategy: Combine with spatie/laravel-backup to backup archive tables separately:

    Backup::create()->archiveTables(['posts_archive'])->storeOnDisk('backups');
    

Config Quirks

  • Connection Mismatch: Ensure the connection in config matches the one used in your models ($connection property).
  • Suffix Collisions: Avoid generic suffixes (e.g., _archive) if multiple packages use the same suffix.
  • Case Sensitivity: Table names are case-sensitive on some databases (e.g., PostgreSQL). Use consistent naming.
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.
aimeos/prisma
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views