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

Rector Laravel Laravel Package

driftingly/rector-laravel

Rector extension for Laravel that applies automated refactors and upgrade rules based on your composer.json or selected Laravel version sets. Includes rules for core Laravel and first‑party packages like Cashier and Livewire.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev driftingly/rector-laravel
    
  2. Basic Configuration (rector.php):

    use Rector\Config\RectorConfig;
    use RectorLaravel\Set\LaravelSetProvider;
    
    return RectorConfig::configure()
        ->withSetProviders(LaravelSetProvider::class)
        ->withComposerBased(laravel: true);
    

    This auto-detects your Laravel version from composer.json and applies the correct upgrade rules.

  3. First Use Case: Run Rector to upgrade from Laravel 11 → 12:

    vendor/bin/rector process src --dry-run
    

    Review changes before committing (--dry-run skips actual file modifications).


Where to Look First

  • Rector Rules Overview: Lists all available rules, including unreleased ones in dev-main.
  • Laravel Version Sets: Check RectorLaravel\Set\LaravelLevelSetList for version-specific rules (e.g., UP_TO_LARAVEL_130).
  • Opinionated Sets: Explore LaravelSetList for code quality improvements (e.g., LARAVEL_COLLECTION, LARAVEL_CODE_QUALITY).

Implementation Patterns

Workflows

  1. Version Upgrade Workflow:

    • Pre-Upgrade: Run Rector with --dry-run to preview changes:
      vendor/bin/rector process src --dry-run --set=LaravelLevelSetList::UP_TO_LARAVEL_130
      
    • Post-Upgrade: After upgrading Laravel, re-run Rector to clean up deprecated patterns:
      vendor/bin/rector process src --set=LaravelSetList::LARAVEL_CODE_QUALITY
      
  2. Incremental Refactoring:

    • Use composer-based detection for automatic version targeting:
      ->withComposerBased(laravel: true, packages: ['livewire/livewire'])
      
    • Combine sets for layered improvements:
      ->withSets([
          LaravelSetList::LARAVEL_STATIC_TO_INJECTION, // Replace facades with DI
          LaravelSetList::LARAVEL_COLLECTION,        // Optimize collections
      ])
      
  3. Testing Integration:

    • Add Rector to CI/CD pipelines (e.g., GitHub Actions) to enforce consistency:
      - name: Run Rector
        run: vendor/bin/rector process src --set=LaravelSetList::LARAVEL_TESTING
      

Integration Tips

  • IDE Support: Use Rector’s --diff flag to generate Git diffs for PRs:
    vendor/bin/rector process src --diff > rector-changes.diff
    
  • Custom Rules: Extend existing rules by creating new ones:
    composer make:rule -- MyCustomRule
    
    Example: Convert Route::get() to controller actions:
    // In `rector.php`
    ->withRules([
        \RectorLaravel\Rector\StaticCall\RouteActionCallableRector::class,
    ])
    
  • Excluding Files/Directories: Skip tests or third-party code:
    ->withPaths([
        __DIR__.'/src',
        __DIR__.'/app',
    ])
    ->withExcludedPaths([
        __DIR__.'/tests',
        __DIR__.'/vendor',
    ])
    

Gotchas and Tips

Pitfalls

  1. False Positives:

    • Rector may misidentify legacy code. Always review changes with --dry-run.
    • Example: RouteActionCallableRector might fail if controller namespaces are non-standard. Fix: Configure the NAMESPACE option:
      ->withConfiguredRule(RouteActionCallableRector::class, [
          'NAMESPACE' => 'App\\Http\\Controllers\\',
      ])
      
  2. Breaking Changes:

    • Some rules (e.g., LARAVEL_STATIC_TO_INJECTION) require manual DI setup in constructors.
    • Tip: Run Rector in batches to avoid overwhelming changes:
      vendor/bin/rector process src --set=LaravelSetList::LARAVEL_FACADE_ALIASES_TO_FULL_NAMES
      
  3. Performance:

    • Large codebases may slow down Rector. Use --parallel for multi-core processing:
      vendor/bin/rector process src --parallel
      

Debugging

  1. Verbose Output: Enable debug mode to trace rule execution:

    vendor/bin/rector process src --verbose
    

    Look for skipped files or failed rules.

  2. Rule-Specific Debugging:

    • Check rector.log for detailed errors.
    • Example: If WhereToWhereLikeRector fails, verify PostgreSQL vs. MySQL syntax:
      ->withConfiguredRule(WhereToWhereLikeRector::class, [
          'USING_POSTGRES_DRIVER' => true,
      ])
      
  3. Skipping Problematic Rules: Exclude a rule temporarily:

    ->withSkippedRules([
        \RectorLaravel\Rector\MethodCall\RemoveModelPropertyFromFactoriesRector::class,
    ])
    

Tips

  1. Leverage dev-main for Early Access: Use the dev-main branch for unreleased rules:

    composer require driftingly/rector-laravel:dev-main
    
  2. Custom Rule Validation: Test new rules in isolation:

    vendor/bin/rector test src/Rector/MyCustomRule.php
    
  3. CI/CD Best Practices:

    • Fail on Changes: Use --fail-on-no-changes to enforce rule application:
      vendor/bin/rector process src --fail-on-no-changes
      
    • Cache Results: Speed up CI with --cache-dir=.rector-cache.
  4. Partial Runs: Target specific files/directories:

    vendor/bin/rector process app/Http/Controllers --set=LaravelSetList::LARAVEL_STATIC_TO_INJECTION
    
  5. Post-Rector Checks: Run PHPStan or Psalm after Rector to validate type safety:

    vendor/bin/phpstan analyse --level=max
    

Extension Points

  1. Create Custom Sets: Combine rules into reusable sets (e.g., app/Rector/CompanySetList.php):

    namespace App\Rector;
    
    use Rector\Set\ValueObject\SetList;
    
    final class CompanySetList extends SetList
    {
        public function getDefinition(): array
        {
            return [
                __DIR__.'/rules/legacy-to-modern.php',
            ];
        }
    }
    

    Then use it in rector.php:

    ->withSets([CompanySetList::class])
    
  2. Override Default Rules: Replace or extend existing rules by implementing RectorInterface:

    use Rector\Core\Contract\Rector\RectorInterface;
    use PhpParser\Node;
    
    final class CustomFacadeRector implements RectorInterface
    {
        public function refactor(Node $node): ?Node
        {
            // Custom logic here
        }
    }
    
  3. Use Rector in Build Processes: Integrate with Laravel’s post-update-cmd in composer.json:

    "scripts": {
        "post-update-cmd": [
            "@php artisan optimize",
            "@vendor/bin/rector process src --set=LaravelSetList::LARAVEL_CODE_QUALITY --dry-run"
        ]
    }
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle