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 Directory Cleanup Laravel Package

spatie/laravel-directory-cleanup

Automatically delete old files from specified directories in Laravel. Configure per-path age limits (in minutes) via a published config file, then run cleanup to keep temp, cache, and upload folders tidy. Supports auto service provider registration in Laravel 5.5+.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The package excels at automated file cleanup in Laravel applications, particularly for:
    • Temporary uploads (e.g., /tmp, /storage/app/public/uploads).
    • Logs (e.g., /storage/logs).
    • Cache directories (e.g., /bootstrap/cache).
    • Media libraries (e.g., /storage/app/media).
  • Event-Driven vs. Scheduled: The package supports both:
    • Manual triggers (e.g., via Artisan commands).
    • Scheduled cleanup (via Laravel’s task scheduler or cron).
  • Config-Driven: Centralized configuration (via config/directory-cleanup.php) allows granular control over retention policies per directory, aligning with 12-factor app principles for ephemeral storage.

Integration Feasibility

  • Laravel Native: Built for Laravel (v8+), leveraging:
    • Service providers (register, boot).
    • Configuration publishing.
    • Artisan commands (php artisan directory:cleanup).
  • Minimal Boilerplate: No complex dependencies; integrates with existing Laravel structures (e.g., config/, app/Console/).
  • Extensibility: Supports custom cleanup logic via events (DirectoryCleanupWillRun, DirectoryCleanupDidRun).

Technical Risk

Risk Area Assessment Mitigation Strategy
File Locking Concurrent processes (e.g., uploads + cleanup) may cause race conditions. Use flock() or Laravel’s Storage::lock() if critical; schedule cleanup during low-traffic periods.
Permission Issues Cleanup may fail if PHP lacks write permissions on target directories. Validate permissions pre-deployment; use chmod/chown in CI/CD or deployment scripts.
Accidental Deletion Misconfigured retention policies could delete critical files. Implement dry-run mode (--dry-run flag) and backup validation (e.g., log deleted files).
Performance Large directories (e.g., millions of files) may slow Laravel. Test with benchmark(); consider chunked processing or queue-based cleanup.
Storage Adapter May not work seamlessly with non-local storage (e.g., S3). Test with spatie/laravel-medialibrary or spatie/laravel-activitylog integrations.

Key Questions

  1. Retention Strategy:
    • Are retention policies static (e.g., "delete files older than 30 days") or dynamic (e.g., tied to user activity)?
    • Should cleanup be time-based or event-based (e.g., post-download)?
  2. Safety Nets:
    • Should deleted files be logged (e.g., to storage/logs/cleanup.log) for auditing?
    • Should a whitelist/blacklist of files/directories be enforced?
  3. Scaling:
    • Will cleanup run locally or in a distributed environment (e.g., Kubernetes)?
    • Should cleanup be parallelized (e.g., per directory)?
  4. Monitoring:
    • How will success/failure of cleanup be alerted (e.g., Slack, Sentry)?
    • Should cleanup metrics (e.g., files deleted, duration) be tracked (e.g., Prometheus)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Core: Works out-of-the-box with Laravel’s service container, config system, and task scheduler.
    • Extensions:
      • Media Libraries: Integrates with spatie/laravel-medialibrary for model-based cleanup.
      • Logging: Complements monolog for audit trails.
      • Queues: Can be wrapped in a job (e.g., CleanupDirectoriesJob) for async processing.
  • Non-Laravel:
    • PHP CLI: Can be used standalone with minimal Laravel dependencies (e.g., for cron jobs).
    • Other Frameworks: Requires manual adaptation (e.g., Symfony’s Console component).

Migration Path

  1. Assessment Phase:
    • Audit target directories (e.g., /storage/app/public/uploads) for:
      • Current retention needs.
      • File volume and growth rate.
      • Permission constraints.
  2. Pilot Deployment:
    • Install via Composer:
      composer require spatie/laravel-directory-cleanup
      
    • Publish config:
      php artisan vendor:publish --provider="Spatie\DirectoryCleanup\DirectoryCleanupServiceProvider"
      
    • Configure config/directory-cleanup.php with test directories (e.g., non-critical logs).
    • Run in dry-run mode:
      php artisan directory:cleanup --dry-run
      
  3. Gradual Rollout:
    • Phase 1: Add to app/Console/Kernel.php for scheduled cleanup:
      protected function schedule(Schedule $schedule)
      {
          $schedule->command('directory:cleanup')->dailyAt('03:00');
      }
      
    • Phase 2: Extend to critical directories (e.g., user uploads) with backup validation.
    • Phase 3: Integrate with monitoring (e.g., log cleanup events to laravel.log).

Compatibility

Component Compatibility Notes
Laravel Version Tested on v8+; may require minor adjustments for v9/10 (e.g., dependency updates).
PHP Version Requires PHP 8.0+ (aligns with Laravel’s minimum).
Storage Adapters Primarily local filesystems; S3/FTP support requires custom logic (e.g., League\Flysystem).
Database No direct DB interaction, but cleanup of DB-backed uploads (e.g., medialibrary) needs coordination.
CI/CD Safe for deployment; avoid running cleanup in CI (e.g., GitHub Actions).

Sequencing

  1. Pre-Integration:
    • Define retention policies (e.g., "Delete uploads older than 90 days").
    • Set up backup procedures for critical directories.
  2. Core Integration:
    • Install package and configure directory-cleanup.php.
    • Implement Artisan command or scheduled task.
  3. Validation:
    • Run dry runs and verify logs.
    • Test edge cases (e.g., symbolic links, hidden files).
  4. Monitoring:
    • Add health checks (e.g., "Last cleanup success" timestamp).
    • Set up alerts for failures (e.g., permission errors).
  5. Optimization:
    • Tune chunk sizes for large directories.
    • Explore parallel processing for distributed setups.

Operational Impact

Maintenance

  • Configuration Management:
    • Retention policies should be version-controlled (e.g., in config/directory-cleanup.php).
    • Use environment-specific configs (e.g., config/directory-cleanup-staging.php) for testing.
  • Dependency Updates:
    • Monitor for Laravel/PHP version compatibility (e.g., via spatie/laravel-package-tools).
    • Update package regularly (e.g., composer update spatie/laravel-directory-cleanup).
  • Documentation:
    • Maintain a runbook for:
      • Common issues (e.g., permission errors).
      • Retention policy changes.
      • Rollback procedures (e.g., restoring deleted files from backups).

Support

  • Troubleshooting:
    • Logs: Enable verbose logging (--verbose flag) for debugging.
    • Common Issues:
      • Permission Denied: Check storage directory permissions (chmod -R 755 storage).
      • Slow Performance: Optimize with find or rsync for large directories.
      • False Deletions: Review directory-cleanup.php for misconfigured paths.
  • Escalation Path:
    • For critical deletions, implement a manual override (e.g., php artisan directory:restore).
    • Use Git blame to track config changes causing unintended deletions.

Scaling

  • Horizontal Scaling:
    • Distributed Cleanup: Run cleanup on each app server (idempotent operations).
    • Locking: Use Laravel’s Cache::lock() to prevent concurrent executions.
  • Vertical Scaling:
    • Resource-Intensive Directories: Offload cleanup to a dedicated worker (e.g., Laravel Horizon).
    • Chunked Processing: Process files in batches (e.g., 1000 files at a time) to avoid memory
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport