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

Livewire Tmp Cleanup Laravel Package

bnzo/livewire-tmp-cleanup

Schedules automatic cleanup of Livewire temporary uploads on S3-compatible disks. Adds the livewire-tmp:clean Artisan command to delete files older than a configurable age, with optional dry-run. Auto-scheduled daily, safe for multi-server deployments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bnzo/livewire-tmp-cleanup
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Bnzo\LivewireTmpCleanup\LivewireTmpCleanupServiceProvider"
    
  2. First Use Case: Run the cleanup manually to test:

    php artisan livewire-tmp:clean --dry-run
    

    Verify output shows files that would be deleted (no actual deletions occur in dry-run mode).

  3. Where to Look First:

    • Config file: config/livewire-tmp-cleanup.php (default: temporary_file_upload disk, 72-hour cleanup).
    • Scheduler: app/Console/Kernel.php (auto-registered LivewireTmpCleanupCommand).
    • Command help: php artisan livewire-tmp:clean --help.

Implementation Patterns

Core Workflow

  1. Configuration: Override defaults in config/livewire-tmp-cleanup.php:

    'disk' => 's3', // Custom disk name
    'directory' => 'livewire-tmp', // Custom path prefix
    'hours' => 24, // Cleanup threshold
    'dry_run' => env('APP_ENV') === 'production' ? false : true, // Force dry-run in staging
    
  2. Scheduling: The package auto-registers a daily cleanup at 03:00 (adjust via schedule() in Kernel.php):

    $schedule->command('livewire-tmp:clean')->dailyAt('03:00')->onOneServer()->withoutOverlapping();
    
  3. Integration with Livewire: Ensure your Livewire components use the same disk for temporary uploads:

    use Livewire\WithFileUploads;
    
    class MyComponent extends Component {
        use WithFileUploads;
    
        public function store() {
            $this->validate([
                'file' => 'required|file',
            ]);
            $this->storeFile('file'); // Uses `temporary_file_upload` disk by default
        }
    }
    
  4. Custom Disks: For non-default disks (e.g., r2), configure in config/filesystems.php and update the package config:

    'disks' => [
        'r2' => [
            'driver' => 's3',
            'key' => env('R2_KEY'),
            'secret' => env('R2_SECRET'),
            'endpoint' => env('R2_ENDPOINT'),
            'bucket' => env('R2_BUCKET'),
            'region' => 'auto',
        ],
    ],
    
  5. Monitoring: Log cleanup results by extending the command (see Gotchas for logging hooks).


Gotchas and Tips

Pitfalls

  1. Dry-Run Misuse:

    • Dry-run (--dry-run) shows what would be deleted but doesn’t log actual files. For debugging, add logging to the command:
      // app/Console/Commands/LivewireTmpCleanupCommand.php
      protected function logCleanup(array $deletedFiles) {
          if ($deletedFiles) {
              Log::info('Deleted ' . count($deletedFiles) . ' files', [
                  'files' => $deletedFiles,
                  'command' => 'livewire-tmp:clean',
              ]);
          }
      }
      
  2. Overlapping Runs:

    • The onOneServer() + withoutOverlapping() guards prevent race conditions in multi-server setups. Disable only if you’re certain the cleanup is safe to run concurrently.
  3. S3 Lifecycle Rules:

    • If you later enable S3 lifecycle rules, stop using this package to avoid double-deletion. The package assumes no other cleanup exists.
  4. Directory Mismatch:

    • Livewire’s default temporary_file_upload directory is livewire-tmp. If you change this in config/filesystems.php, update the package config to match:
      'directory' => 'custom-livewire-tmp', // Must match your disk config
      
  5. Large Buckets:

    • Cleanup may time out for buckets with >100K files. Test with --limit=1000 to simulate batch processing:
      php artisan livewire-tmp:clean --limit=1000
      

Debugging Tips

  1. Verify Disk Connection: Test your S3 disk manually:

    php artisan storage:link --force
    php artisan tinker
    >>> \Storage::disk('s3')->files('livewire-tmp');
    
  2. Check File Ages: Use aws s3api list-objects (AWS) or R2 CLI to confirm file timestamps match your hours threshold.

  3. Permissions: Ensure your IAM/R2 user has s3:DeleteObject permissions for the target bucket.

Extension Points

  1. Custom Cleanup Logic: Extend the command to add filters (e.g., skip files with specific prefixes):

    // app/Console/Commands/LivewireTmpCleanupCommand.php
    protected function shouldDelete(File $file) {
        return $file->lastModified() < now()->subHours($this->hours)
            && ! Str::startsWith($file->path(), 'livewire-tmp/protected/');
    }
    
  2. Event-Based Cleanup: Trigger cleanup after specific actions (e.g., user logout) via a listener:

    // app/Providers/EventServiceProvider.php
    public function boot() {
        UserLoggedOut::listen(function () {
            Artisan::call('livewire-tmp:clean', ['--force' => true]);
        });
    }
    
  3. Slack/Email Notifications: Add alerts for cleanup failures:

    // In the command's handle() method
    try {
        $this->clean();
    } catch (\Exception $e) {
        Notification::route('slack', config('services.slack.webhook'))
            ->notify(new CleanupFailed($e));
    }
    
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.
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
sandermuller/package-boost-php
sandermuller/boost-core
depa/sulu-google-reviews-bundle
croct/plug-symfony
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard