Rector in Practice: Automating Laravel Code Modernization for Developers

The process of developing a massive application is termed as a race against time. As the framework advances, your code may become obsolete in a matter of time, resulting in technical debt that hinders the development of new features. When you are set to refactor Laravel with Rector, you are looking for the most efficient way to make your application fresh and fast. The digital architect has the ability to scan files instantly, resulting in the automation of Laravel code refactoring without any hassle.

What is Code Refactoring?

Refactoring code is the art of reorganizing already written code without altering the way it works. While it primarily deals with the design, it makes the code more readable in an attempt to optimize it for your developers. Refactoring the code would be like polishing the engine of the car when the car is running.

Manual code refactoring introduces the possibility of human error. The process takes a tremendous amount of time and could be spent on adding functionality. When done by hand, there is a possible introduction of bugs. Tracking these bugs in a large code base can be a nightmare.

Setting the Stage: Installation and Setup

Before you can modernizing legacy Laravel codebase components, you need to add the right tools to your project. Most developers prefer using Composer to manage these dependencies. You will need both the core engine and the Laravel-specific extension to get the best results.

Run the following commands in your terminal:

composer require rector/rector --dev

composer require driftingly/rector-laravel --dev

Once the installation finishes, generate your configuration file into root directory by name rector.php. This file will acts as the control center for your automation rules.

Configuring Rector for Laravel Specifics

Laravel has unique patterns like Facades, Eloquent models, and specific helper functions. To refactor Laravel with Rector effectively, you should include the rector-laravel ruleset. This ensures the tool understands how your framework functions and applies the correct transformations.

Open your rector.php file and use the LaravelSetList to pick your desired improvements. You can also define specific paths like app, config, and tests to ensure the tool analyzes the right files.

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use RectorLaravel\Set\LaravelLevelSetList;
use RectorLaravel\Set\LaravelSetList;

return RectorConfig::configure()
    ->withPaths([
        __DIR__.'/app',
        __DIR__ . '/config',
        __DIR__ . '/database',
        __DIR__ . '/routes',
        __DIR__.'/tests',
    ])
    ->withSets([
        LaravelLevelSetList::UP_TO_LARAVEL_120,
        LaravelSetList::LARAVEL_CODE_QUALITY,
        LaravelSetList::LARAVEL_COLLECTION,
        LaravelSetList::LARAVEL_IF_HELPERS,
    ])
    ->withPhpSets(php83: true)
    ->withPreparedSets(
        deadCode: true,
        typeDeclarations: true,
        privatization: true,
        earlyReturn: true
    )
    ->withSkip([
        __DIR__.'/bootstrap/cache',
        __DIR__.'/storage',
        __DIR__.'/vendor',
    ]);

In this example, we have added app, config, database, routes and tests directory for refactoring. However, we have also set some directory to skip like storage and vendor.

Here, we have used predefined set list for laravel like rules for Laravel 12, code quality, collection methods and if helpers. Those rule will check your code and help rector to improve your code standard.

In Practice: Running Your First Analysis

It is time to see the tool in action. Most experts recommend running a “dry run” first. This allows you to see the proposed changes without actually modifying any files. Use the following command to start the analysis:

vendor/bin/rector process --dry-run

For simple understanding, you have to dry run process. It will show diff for updated code. . You will see red lines for the old code and green lines for the new, modernized version. This step is crucial because it gives you full control over the transformation process before any permanent changes occur.

To modify files and update code, you need to run below command:

vendor/bin/rector process

It will take some time to process based on you files.

Transformation Example

Imagine you are upgrading Laravel applications with rector and come across old-school controller logic. The tool can automatically convert old helper calls into modern, fluent syntax.

/** * Example 1: Modernizing Redirects and Conditionals
 * Before: return redirect()->route('home');
 * Before: if ($user->is_banned) { abort(403); }
 **/
return to_route('home');
abort_if($user->is_banned, 403);

/** * Example 2: Eloquent and Collection Refactoring
 * Before: $emails = User::all()->map(fn($user) => $user->email);
 **/
$emails = User::pluck('email');

/** * Example 3: String and Array Helpers
 * Before: $slug = str_slug($title);
 * Before: $value = array_get($data, 'key');
 **/
$slug = \Illuminate\Support\Str::slug($title);
$value = $data['key'] ?? null;

/** * Example 4: Constructor Property Promotion (PHP 8+)
 * Before: private $service; public function __construct($service) { $this->service = $service; }
 **/
public function __construct(
    private readonly \App\Services\PaymentService $service
) {}

/** * Example 5: Environment and Config Helpers
 * Before: if (env('APP_ENV') === 'production')
 **/
if (app()->environment('production'))

As you can see in above example, we have use some common example of rectoring.

Additional Customization

The true power of a rector laravel is in the flexibility. You can choose specific sets such as LARAVEL_CODE_QUALITY or LARAVEL_COLLECTION to target certain areas of your app. Even if you are using Lumen then this package has rules for that. If you have a custom internal library, you can even write your own rules to automate company-specific migrations.

To streamline your development cycle, you can chain these tools within your composer.json scripts to automate Laravel code refactoring, styling, and testing in a single stroke. This approach ensures that after you refactor Laravel with Rector, your code is immediately polished by Laravel Pint for style consistency and verified by Pest for functional integrity. Combining these powerful utilities allows you to maintain a modernizing legacy Laravel codebase workflow that is both fast and remarkably safe.

"scripts": {
    "modernize": "vendor/bin/rector process && vendor/bin/pint && ./vendor/bin/pest"
}

Conclusion

Embracing automated Laravel version upgrade tools is the only way to stay competitive. By using these tools, you transform a daunting upgrade task into a manageable, repeatable process. You save time, reduce bugs, and allow your developers to focus on creativity rather than syntax corrections. Start small, run your tests, and watch your codebase transform into a modern masterpiece.