You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel7升级10后,路由字符串转可调用语法及Rector报错解决

Laravel 7升级至10后批量转换路由为可调用语法的方法

问题背景

项目已从Laravel 7升级到Laravel 10,routes/web.php中存在大量路由,需要批量将这些路由转换为Laravel 8+引入的可调用语法,寻求简便实现方案。

尝试Laravel Rector转换及报错

尝试使用Laravel Rector工具进行自动转换,初始配置的rector.php内容如下:

<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\Config\RectorConfig;
use RectorLaravel\Rector\StaticCall\RouteActionCallableRector;
use Rector\Set\ValueObject\LevelSetList;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__ . '/routes'
    ]);

    $rectorConfig->ruleWithConfiguration(RouteActionCallableRector::class, [
        RouteActionCallableRector::NAMESPACE => 'App\Http\Controllers',
    ]);
};

执行命令 vendor/bin/rector process src 时出现以下错误:

[ERROR] Cannot autowire service "RectorLaravel\Rector\StaticCall\RouteActionCallableRector": argument                  
         "$routerRegisterNodeAnalyzer" of method "__construct()" references class
         "RectorLaravel\NodeFactory\RouterRegisterNodeAnalyzer" but no such service exists.

问题解决

在配置文件底部添加Laravel代码质量集合后,问题得到解决,修改后的rector.php配置如下:

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__ . '/routes'
    ]);

    $rectorConfig->ruleWithConfiguration(RouteActionCallableRector::class, [
        RouteActionCallableRector::NAMESPACE => 'App\Http\Controllers',
    ]);

    // added this
    $rectorConfig->sets([
        LaravelSetList::LARAVEL_CODE_QUALITY
    ]);
};

转换成功完成,但工具生成的路由会使用控制器的完整类路径(如 'App\Http\Controllers\SomeController'),而非仅类名加顶部use语句引入的形式,不过这个问题可以手动快速修复。


内容的提问来源于stack exchange,提问作者pileup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:48:13