PHPackages                             codemonkey76/laravel-legacy-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. codemonkey76/laravel-legacy-cleaner

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

codemonkey76/laravel-legacy-cleaner
===================================

Detect and manager unused/legacy code in Laravel applications

v1.0.4(6mo ago)1104[1 issues](https://github.com/codemonkey76/laravel-legacy-cleaner/issues)MITPHPPHP ^8.1

Since Nov 27Pushed 6mo agoCompare

[ Source](https://github.com/codemonkey76/laravel-legacy-cleaner)[ Packagist](https://packagist.org/packages/codemonkey76/laravel-legacy-cleaner)[ RSS](/packages/codemonkey76-laravel-legacy-cleaner/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (5)Versions (15)Used By (0)

Laravel Legacy Cleaner
======================

[](#laravel-legacy-cleaner)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9b35ed475644a6974a768d05426399c9a6aced2cb02a5703c2161d67ef93e8f1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64656d6f6e6b657937362f6c61726176656c2d6c65676163792d636c65616e65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonkey76/laravel-legacy-cleaner)[![Total Downloads](https://camo.githubusercontent.com/e57ce7657bd5f875aa980f2c05273c5b66a3e463c592729b7c82ede47fca8003/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f64656d6f6e6b657937362f6c61726176656c2d6c65676163792d636c65616e65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codemonkey76/laravel-legacy-cleaner)

A powerful Laravel package to detect and manage unused/legacy code in your Laravel applications. Helps you identify unused controllers, models, routes, and views to keep your codebase clean and maintainable.

Features
--------

[](#features)

- 🔍 **Analyze Controllers** - Find unused controllers and methods
- 📦 **Analyze Models** - Detect unused Eloquent models
- 🛣️ **Analyze Routes** - Identify unused routes
- 👁️ **Analyze Views** - Find unused Blade templates
- 📊 **Generate Reports** - Create comprehensive HTML, JSON, or Markdown reports
- 🗄️ **Archive Unused Code** - Safely move unused code to an archive directory
- ⚙️ **Configurable** - Customize paths, exclusions, and search patterns

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x, 11.x, or 12.x

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

[](#installation)

Install the package via Composer:

```
composer require codemonkey76/laravel-legacy-cleaner --dev
```

Publish the configuration file (optional):

```
php artisan vendor:publish --tag=legacy-cleaner-config
```

This will create a `config/legacy-cleaner.php` file where you can customize the package settings.

Usage
-----

[](#usage)

### Analyze Controllers

[](#analyze-controllers)

Find unused controllers and methods in your application:

```
# Basic analysis
php artisan legacy:analyze-controllers

# Show unused methods in used controllers
php artisan legacy:analyze-controllers --show-methods

# Export results to JSON
php artisan legacy:analyze-controllers --format=json --output=storage/controllers.json

# Export to CSV
php artisan legacy:analyze-controllers --format=csv --output=storage/controllers.csv
```

**Output:**

```
Analyzing controllers...

📊 Summary:
+---------------------+-------+
| Metric              | Count |
+---------------------+-------+
| Total Controllers   | 25    |
| Used Controllers    | 20    |
| Unused Controllers  | 5     |
| Unused Percentage   | 20%   |
+---------------------+-------+

⚠️  Found 5 potentially unused controllers:

```

### Analyze Models

[](#analyze-models)

Detect unused Eloquent models:

```
# Basic analysis
php artisan legacy:analyze-models

# Also check if database tables exist
php artisan legacy:analyze-models --check-tables

# Export results
php artisan legacy:analyze-models --format=json --output=storage/models.json
```

**Features:**

- Finds models with no code references
- Counts relationships defined in models
- Optionally verifies database table existence
- Reports used models with missing tables

### Analyze Routes

[](#analyze-routes)

Identify unused routes:

```
# Analyze all routes
php artisan legacy:analyze-routes

# Export results
php artisan legacy:analyze-routes --format=json --output=storage/routes.json
```

The analyzer searches for route usage in:

- Blade views (`route('name')`)
- JavaScript files
- Direct URI references
- Controller redirects

### Analyze Views

[](#analyze-views)

Find unused Blade templates:

```
# Analyze views (excluding partials)
php artisan legacy:analyze-views

# Include partial views in analysis
php artisan legacy:analyze-views --include-partials

# Export results
php artisan legacy:analyze-views --format=json --output=storage/views.json
```

**View Types Detected:**

- Layouts (`resources/views/layouts/*`)
- Components (`resources/views/components/*`)
- Partials (files starting with `_`)
- Regular views

The analyzer searches for:

- `view()` helper calls
- `View::make()` calls
- `@extends`, `@include`, `@component` directives
- `` usage
- `Inertia::render()` calls

### Generate Comprehensive Report

[](#generate-comprehensive-report)

Create a full analysis report in multiple formats:

```
# Generate HTML report (default)
php artisan legacy:report

# Generate JSON report
php artisan legacy:report --format=json

# Generate Markdown report
php artisan legacy:report --format=markdown

# Specify output location
php artisan legacy:report --output=storage/app/reports/legacy-analysis.html
```

**HTML Report Features:**

- Beautiful, responsive design
- Summary statistics for each category
- Color-coded results
- Sortable tables
- Timestamp of generation

### Archive Unused Code

[](#archive-unused-code)

Safely move unused code to an archive directory:

```
# Preview what would be archived (dry run)
php artisan legacy:archive --dry-run

# Archive unused controllers
php artisan legacy:archive

# Archive specific types
php artisan legacy:archive --type=controllers --type=views
```

**Safety Features:**

- Confirmation prompt before archiving
- Dry-run mode to preview changes
- Preserves directory structure in archive
- Optional backup before archiving (configurable)

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

[](#configuration)

After publishing the config file (`config/legacy-cleaner.php`), you can customize:

### Paths to Analyze

[](#paths-to-analyze)

```
'paths' => [
    'controllers' => app_path('Http/Controllers'),
    'models' => app_path('Models'),
    'views' => resource_path('views'),
    'routes' => base_path('routes'),
    'middleware' => app_path('Http/Middleware'),
    'requests' => app_path('Http/Requests'),
    'jobs' => app_path('Jobs'),
],
```

### Exclusions

[](#exclusions)

Exclude specific files or patterns from analysis:

```
'exclude' => [
    'controllers' => [
        'Controller.php',  // Base controller
    ],
    'routes' => [
        'api.*',           // Exclude all API routes
        'admin.*',         // Exclude admin routes
    ],
],
```

### Archive Settings

[](#archive-settings)

```
'archive' => [
    'enabled' => true,
    'path' => app_path('Archive'),
    'backup_before_archive' => true,
],
```

### Report Settings

[](#report-settings)

```
'report' => [
    'output_path' => storage_path('app/legacy-cleaner'),
    'format' => 'html', // html, json, markdown
],
```

### Custom Search Patterns

[](#custom-search-patterns)

Define custom patterns for finding code usage:

```
'search_patterns' => [
    'route_usage' => [
        "route\(['\"]%s['\"]",
        "Route::get\(['\"]%s['\"]",
        "redirect\(\)->route\(['\"]%s['\"]",
    ],
    'controller_usage' => [
        "use %s;",
        "%s::class",
        "new %s",
    ],
],
```

Command Reference
-----------------

[](#command-reference)

CommandDescriptionOptions`legacy:analyze-controllers`Analyze controllers`--show-methods`, `--format`, `--output``legacy:analyze-models`Analyze models`--check-tables`, `--format`, `--output``legacy:analyze-routes`Analyze routes`--format`, `--output``legacy:analyze-views`Analyze views`--include-partials`, `--format`, `--output``legacy:report`Generate comprehensive report`--format`, `--output``legacy:archive`Archive unused code`--dry-run`, `--type`How It Works
------------

[](#how-it-works)

### Controller Analysis

[](#controller-analysis)

1. Scans all PHP files in the controllers directory
2. Checks if controllers are referenced in routes
3. Searches for controller usage in codebase (imports, instantiation)
4. Identifies unused public methods in controllers

### Model Analysis

[](#model-analysis)

1. Finds all classes extending `Illuminate\Database\Eloquent\Model`
2. Searches for model references in controllers, views, and routes
3. Counts defined relationships
4. Optionally checks if corresponding database tables exist

### Route Analysis

[](#route-analysis)

1. Retrieves all registered routes
2. Searches for route name usage in Blade views
3. Searches for route usage in JavaScript files
4. Looks for direct URI references

### View Analysis

[](#view-analysis)

1. Scans Blade template files
2. Categorizes views (layouts, components, partials, regular views)
3. Searches for view references in controllers
4. Checks for `@extends`, `@include`, component usage
5. Detects Inertia.js usage

Best Practices
--------------

[](#best-practices)

### Before Archiving

[](#before-archiving)

1. **Always run with `--dry-run` first**

    ```
    php artisan legacy:archive --dry-run
    ```
2. **Review the analysis carefully** - Some code might appear unused but could be:

    - Called dynamically
    - Used in external packages
    - Required for future features
    - API endpoints called by mobile apps
3. **Generate a report for documentation**

    ```
    php artisan legacy:report --output=reports/pre-cleanup-$(date +%Y%m%d).html
    ```
4. **Commit your changes** before archiving

### Regular Maintenance

[](#regular-maintenance)

Run analysis regularly (e.g., monthly) to:

- Keep track of code health
- Identify bloat early
- Monitor technical debt
- Plan refactoring efforts

### CI/CD Integration

[](#cicd-integration)

Add to your CI pipeline:

```
# .github/workflows/code-analysis.yml
- name: Analyze Legacy Code
  run: |
    php artisan legacy:analyze-controllers --format=json --output=controllers.json
    php artisan legacy:analyze-models --format=json --output=models.json
```

Limitations
-----------

[](#limitations)

### False Positives

[](#false-positives)

The package may report false positives for:

- **Dynamic code execution** - Code called via `call_user_func`, variable functions
- **External API routes** - Routes only called by mobile apps or external services
- **Event-driven code** - Code triggered by events/listeners
- **Reflection-based usage** - Code loaded via reflection
- **String-based references** - `view("some.{$variable}.path")`

### Not Detected

[](#not-detected)

The analyzer cannot detect:

- Code called from package service providers
- Routes/views defined in external packages
- Usage in JavaScript frameworks (Vue, React) with complex routing
- Database migrations and seeders

Troubleshooting
---------------

[](#troubleshooting)

### "Class not found" errors

[](#class-not-found-errors)

Make sure your autoloader is up to date:

```
composer dump-autoload
```

### Large codebases timing out

[](#large-codebases-timing-out)

Increase PHP memory limit and max execution time:

```
php -d memory_limit=512M -d max_execution_time=300 artisan legacy:analyze-controllers
```

### Missing results

[](#missing-results)

Check your configuration:

```
// Verify paths in config/legacy-cleaner.php
'paths' => [
    'controllers' => app_path('Http/Controllers'),
    // ...
],
```

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

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

### Development Setup

[](#development-setup)

```
git clone https://github.com/codemonkey76/laravel-legacy-cleaner.git
cd laravel-legacy-cleaner
composer install
```

### Running Tests

[](#running-tests)

```
composer test
```

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Shane Poppleton](https://github.com/codemonkey76)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Support
-------

[](#support)

If you find this package helpful, please consider:

- ⭐ Starring the repository
- 🐛 Reporting bugs
- 💡 Suggesting new features
- 📖 Improving documentation

---

**Made with ❤️ for the Laravel community**

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance46

Moderate activity, may be stable

Popularity13

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

14

Last Release

206d ago

Major Versions

v0.2.6 → v1.0.12025-12-09

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3654457?v=4)[Shane Poppleton](/maintainers/codemonkey76)[@codemonkey76](https://github.com/codemonkey76)

---

Top Contributors

[![codemonkey76](https://avatars.githubusercontent.com/u/3654457?v=4)](https://github.com/codemonkey76 "codemonkey76 (17 commits)")

---

Tags

laravelrefactoringunused codecode analysisLegacy code

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/codemonkey76-laravel-legacy-cleaner/health.svg)

```
[![Health](https://phpackages.com/badges/codemonkey76-laravel-legacy-cleaner/health.svg)](https://phpackages.com/packages/codemonkey76-laravel-legacy-cleaner)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.5k55.4M8.4k](/packages/larastan-larastan)[laravel/sail

Docker files for running a basic Laravel application.

1.9k205.7M1.3k](/packages/laravel-sail)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M194](/packages/laravel-ai)[livewire/flux

The official UI component library for Livewire.

9527.8M127](/packages/livewire-flux)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M151](/packages/laravel-mcp)[propaganistas/laravel-disposable-email

Disposable email validator

6023.0M6](/packages/propaganistas-laravel-disposable-email)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
