PHPackages                             gabrielstack/laravel-cache-cleaner - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. gabrielstack/laravel-cache-cleaner

ActiveLibrary[Caching](/categories/caching)

gabrielstack/laravel-cache-cleaner
==================================

Laravel Artisan command for cleaning expired file cache entries - PHP 8.0+ compatible

013PHP

Since Oct 3Pushed 7mo agoCompare

[ Source](https://github.com/Gabriel-stack/laravel-clear-cache-file)[ Packagist](https://packagist.org/packages/gabrielstack/laravel-cache-cleaner)[ RSS](/packages/gabrielstack-laravel-cache-cleaner/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Cache Cleaner
=====================

[](#laravel-cache-cleaner)

A Laravel package that provides an Artisan command for cleaning expired file cache entries in the `storage/framework/cache/data` directory. Designed specifically for Laravel projects with seamless integration.

Features
--------

[](#features)

- 🎯 **Laravel Artisan Command**: Native `php artisan cache:clean-files` command
- 🧹 **Smart Cleaning**: Automatically detects and removes expired cache files
- 🛡️ **Memory Efficient**: Handles large cache directories without memory issues
- 🔧 **Laravel Integration**: Uses Laravel's service provider auto-discovery
- ⚡ **Fast Performance**: Optimized directory traversal and file operations
- 📊 **Beautiful Output**: Formatted tables and progress indicators
- 🔒 **Safe**: Only processes Laravel's file cache format

Installation
------------

[](#installation)

Install via Composer:

```
composer require clear-cache-file/laravel-cache-cleaner
```

The service provider will be automatically registered via Laravel's package auto-discovery.

Usage
-----

[](#usage)

### Basic Command

[](#basic-command)

```
# Clean expired cache files
php artisan cache:clean-files
```

### Command Options

[](#command-options)

```
# Show detailed output (using Laravel's built-in verbose option)
php artisan cache:clean-files --verbose

# Use custom cache directory
php artisan cache:clean-files --path=/custom/cache/path

# Dry run - analyze without deleting files
php artisan cache:clean-files --dry-run

# Combined options
php artisan cache:clean-files --verbose --path=/custom/path --dry-run
```

> **Note**: The `--verbose` option is provided automatically by Laravel's console framework and doesn't need to be defined in the command signature.

### Laravel Cache Directory

[](#laravel-cache-directory)

This package targets Laravel's file cache directory:

```
laravel-project/
├── storage/
│   └── framework/
│       └── cache/
│           └── data/  ← This directory
│               ├── 1640995200somekey
│               ├── 1640995300anotherkey
│               └── ...

```

Command Output
--------------

[](#command-output)

The command provides beautiful, formatted output:

### Normal Cleanup

[](#normal-cleanup)

```
🧹 Laravel File Cache Cleaner
Cleaning expired cache files...

Cache directory: /var/www/laravel/storage/framework/cache/data

┌─────────────────────┬─────────────┐
│ Metric              │ Value       │
├─────────────────────┼─────────────┤
│ Files deleted       │ 1,234       │
│ Space freed         │ 15.67 MB    │
│ Directories removed │ 5           │
│ Time taken          │ 0.23 seconds│
└─────────────────────┴─────────────┘

🗑️  Removed 1,234 expired cache files
💾 Freed 15.67 MB of disk space
✅ Cache cleanup completed successfully!

```

### Dry Run Mode

[](#dry-run-mode)

```
🧹 Laravel File Cache Cleaner (DRY RUN)
Analyzing expired cache files (no files will be deleted)...

Cache directory: /var/www/laravel/storage/framework/cache/data
Running in DRY RUN mode - no files will actually be deleted

┌──────────────────────────────────────────────────────┬─────────────┐
│ Metric                                    │ Value       │
├──────────────────────────────────────────────────────┼─────────────┤
│ Files that would be deleted              │ 1,234       │
│ Space that would be freed                │ 15.67 MB    │
│ Directories that would be removed        │ 5           │
│ Time taken                               │ 0.23 seconds│
└──────────────────────────────────────────────────────┴─────────────┘

📊 Found 1,234 expired cache files that could be removed
💾 15.67 MB of disk space could be freed
✅ Cache analysis completed successfully!

```

Dry Run Mode
------------

[](#dry-run-mode-1)

Use the `--dry-run` option to analyze your cache without actually deleting any files. This is perfect for:

- **Assessment**: See how much space could be freed before cleanup
- **Monitoring**: Regular analysis without affecting cache files
- **Safety**: Verify the command works correctly before actual cleanup
- **Reporting**: Generate metrics for system monitoring

```
# Analyze cache files without deleting
php artisan cache:clean-files --dry-run --verbose
```

In dry-run mode, the command will:

- ✅ Scan all cache files and identify expired ones
- ✅ Calculate total file sizes and directory counts
- ✅ Show detailed analysis results
- ❌ **NOT** delete any files or directories
- ❌ **NOT** modify the cache in any way

Scheduling
----------

[](#scheduling)

Add to your `app/Console/Kernel.php` to schedule automatic cleanup:

```
protected function schedule(Schedule $schedule)
{
    // Clean cache daily at 3 AM
    $schedule->command('cache:clean-files')
             ->daily()
             ->at('03:00');

    // Or clean every hour
    $schedule->command('cache:clean-files')
             ->hourly();
}
```

Cache File Format
-----------------

[](#cache-file-format)

Laravel stores cache files with this format:

- **First 10 characters**: Unix timestamp (expiration time)
- **Remaining content**: Serialized cache data

Example: `1640995200somedata` (expires at timestamp 1640995200)

Service Provider
----------------

[](#service-provider)

The package includes a service provider that automatically registers the command:

```
// CacheCleanerServiceProvider automatically registers:
$this->commands([
    CacheCleanFilesCommand::class,
]);
```

Configuration
-------------

[](#configuration)

No configuration files needed! The package works out of the box with Laravel's default cache configuration.

Error Handling
--------------

[](#error-handling)

The command provides proper error handling with descriptive messages:

```
❌ Cache cleanup failed: Laravel cache directory does not exist: /path/to/cache
```

Exit codes:

- `0`: Success
- `1`: Failure

### Common Issues

[](#common-issues)

#### "An option named 'verbose' already exists"

[](#an-option-named-verbose-already-exists)

This error occurs when the `--verbose` option is manually defined in the command signature. The `--verbose` option is automatically provided by Laravel's console framework and should not be redefined.

**Solution**: Remove `{--verbose : Show detailed output}` from the command signature - Laravel provides this option automatically.

Backward Compatibility
----------------------

[](#backward-compatibility)

The package still includes the old static methods for backward compatibility, but they are deprecated:

```
// ❌ Deprecated (still works)
$stats = CacheCleaner::clean('/path/to/laravel');

// ✅ Recommended
// php artisan cache:clean-files
```

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- Laravel 8.0 or higher
- File system read/write permissions

Supported Laravel Versions
--------------------------

[](#supported-laravel-versions)

- Laravel 8.x
- Laravel 9.x
- Laravel 10.x
- Laravel 11.x

Testing
-------

[](#testing)

Run the package tests:

```
composer test
```

Performance
-----------

[](#performance)

- **Memory Efficient**: Uses iterators for large directories
- **Race Condition Safe**: Handles concurrent access gracefully
- **Optimized I/O**: Minimal disk operations for maximum speed

Tested with Laravel cache directories containing 100,000+ cache files.

Examples
--------

[](#examples)

See the `examples/` directory for detailed usage examples:

- `artisan_command_example.php`: How to use the Artisan command
- `laravel_cache_example.php`: Legacy usage examples
- `laravel_scheduled_cleanup.php`: Scheduled cleanup setup

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) file for details.

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for version history and changes.

Quick Start
-----------

[](#quick-start)

### Basic Laravel Cache Cleaning

[](#basic-laravel-cache-cleaning)

```
