为 Laravel 8 路由定义命名空间

Are*_* TG 5 php laravel

关于 Laravel 8.x 路由的问题

现在我在 web.php 文件中添加这样的行:

use App\Http\Controllers\FirstController;
use App\Http\Controllers\SecondController;
use App\Http\Controllers\ThirdController;
Run Code Online (Sandbox Code Playgroud)

然后只是工作FirstController::class等等。

在开始时一个接一个地使用 x 次namespace App\Http\Controllers;而不是所有use行是错误的吗?

谢谢。

Del*_*D0D 10

相反,我只是取消注释这一行,其中app/Providers/RouteServiceProvider.php将恢复到自动在命名空间中为路由声明添加前缀的 Laravel <8'routes/web.php' 'routes/api.php' 行为App\Http\Controllers

/**
 * The controller namespace for the application.
 *
 * When present, controller route declarations will automatically be prefixed with this namespace.
 *
 * @var string|null
 */
 protected $namespace = 'App\\Http\\Controllers';
Run Code Online (Sandbox Code Playgroud)

如果您在 v8 首次发布时创建了该项目,则此注释掉的属性可能不在您的中app/Providers/RouteServiceProvider.php(似乎已将其删除然后又添加回来)如果没有,只需添加它并取消commnet,并确保它在bootprop 和 it 的方法中使用会工作的。

public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)           // make sure this is present
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace)            // make sure this is present
            ->group(base_path('routes/web.php'));
    });
}
Run Code Online (Sandbox Code Playgroud)