Code quality and maintainability are crucial aspects of modern software development.
In this post, I’ll show you how to set up .
Why Use Rector in Your Laravel Project?
Automates Upgrades: Keep your codebase compatible with the latest Laravel or PHP versions.
Improves Code Quality: Applies rules to clean up and optimize your code automatically.
Saves Time: Refactors code in minutes, letting developers focus on business logic.
Setting Up Rector in Your Laravel Project
Step 1: Install Rector and Laravel-Specific Rules
Install Rector and its Laravel extension using Composer:
composer require rector/rector --dev
composer require driftingly/rector-laravel --dev
Step 2: Configure Rector
Create a rector.php configuration file in your project root if it’s not already present. Below is an example configuration tailored for Laravel projects:
<?php
declare(strict_types=1);
use Rector\Caching\ValueObject\Storage\FileCacheStorage;
use Rector\CodeQuality\Rector\FuncCall\CompactToVariablesRector;
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\SetList;
use Rector\ValueObject\PhpVersion;
use RectorLaravel\Set\LaravelLevelSetList;
return static function (RectorConfig $rectorConfig): void {
// Paths to analyze
$rectorConfig->paths([
__DIR__.'/app',
__DIR__.'/config',
__DIR__.'/database',
__DIR__.'/resources',
__DIR__.'/routes',
__DIR__.'/tests',
]);
// Skip specific rules
$rectorConfig->skip([
CompactToVariablesRector::class,
]);
// Enable caching for Rector
$rectorConfig->cacheDirectory(__DIR__.'/storage/rector');
$rectorConfig->cacheClass(FileCacheStorage::class);
// Apply sets for Laravel and general code quality
$rectorConfig->sets([
LaravelLevelSetList::UP_TO_LARAVEL_110,
SetList::CODE_QUALITY,
]);
// Define PHP version for Rector
$rectorConfig->phpVersion(PhpVersion::PHP_83);
};
Step 3: Test Rector Locally
Run Rector locally to ensure everything is configured properly:
vendor/bin/rector process --dry-run --ansi
The --dry-run flag previews the changes without modifying the files.
.
Conclusion
With Rector and GitHub Actions, your Laravel project stays modern, clean, and maintainable. This automated setup saves hours of manual refactoring, keeping your codebase aligned with the latest standards. Ready to implement Rector in your project? Let me know how it goes, or feel free to share your experience!
Happy coding! 🚀
Photo by
SOCIAL SHARE CARD GENERATOR