Keeping a Laravel project up to date and maintaining clean code can become costly as it grows. This is where Rector becomes a key tool.
Rector is an automation tool that analyzes and refactors your PHP code safely. It allows you to apply modern improvements, adapt your code to new PHP or Laravel versions, and remove deprecated patterns automatically.
Why use Rector in Laravel?
In a Laravel project, Rector can help you:
- Upgrade legacy code to newer PHP or Laravel versions
- Apply best practices consistently
- Reduce human error during large refactors
All of this without changing your application’s behavior.
Basic steps to get started with Rector in Laravel
1. Install Rector and the Laravel extension as a development dependency
composer require rector/rector --dev
composer require --dev driftingly/rector-laravel
2. Create the configuration file (rector.php) at project's root
Define the PHP version, Laravel rules, and the directories to analyze.
declare(strict_types=1);
use Rector\Config\RectorConfig;
use RectorLaravel\Rector\FuncCall\RemoveDumpDataDeadCodeRector;
use RectorLaravel\Rector\StaticCall\DispatchToHelperFunctionsRector;
use RectorLaravel\Set\LaravelLevelSetList;
use RectorLaravel\Set\LaravelSetList;
return RectorConfig::configure()
->withPaths([
__DIR__ . '/app',
__DIR__ . '/tests',
])
->withPhpSets(php84: true)
->withSets([
LaravelLevelSetList::UP_TO_LARAVEL_120,
LaravelSetList::LARAVEL_CODE_QUALITY,
LaravelSetList::LARAVEL_COLLECTION,
])
->withConfiguredRule(RemoveDumpDataDeadCodeRector::class, ['dd', 'dump', 'var_dump'])
->withSkip([DispatchToHelperFunctionsRector::class]);
3. Run Rector in dry-run mode (--dry-run)
Review the proposed changes before applying them.
./vendor/bin/rector process --dry-run
4. Apply changes
Start with safe rules and avoid doing everything at once on large projects.
./vendor/bin/rector process
5. Run your tests
Make sure the application behavior remains unchanged.
php artisan test
A day-to-day ally
Rector doesn’t replace code reviews or tests, but it’s a great ally for keeping your codebase healthy over time. You can run it occasionally or integrate it into your regular workflow.
If you work with Laravel and want to evolve your project with confidence, Rector is well worth it.