php - Laravel 9 未定义类 'MainController' 一旦取消注释 RouteServiceProvider 中的 Controller 命名空间

标签 php laravel laravel-9

我全新安装了 Laravel 9,并尝试在 RouteServiceProvider.php 中取消注释 Controller namespace 。但在我的 api 路由中抛出错误:

Undefined class 'MainController'

我的 Controller 已正确放置在该命名空间下。

App\Http\Controllers

api.php文件是这样的。

Route::group(['prefix' => '/main'], function () {
Route::get('/', [MainController::class, 'index']);
});

Controller 文件是这样的。

<?php

namespace App\Http\Controllers;

class MainController extends Controller
{
  public function index()
  {
    return response()->json(['status'=>200,'message'=>'success']);
  }
}

如果我将 Controller 文件导入 api 路由文件,它会正常工作。

最佳答案

只需将以下内容添加到您的 RouteServiceProvider 中,它仍然可以工作。它已从最新版本中删除,但您可以再次添加回来。

/**
 * 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';

然后使您的启动方法如下所示。

/**
 * Define your route model bindings, pattern filters, and other route configuration.
 *
 * @return void
 */
public function boot()
{
    $this->configureRateLimiting();

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

        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    });
}

这就是您需要做的所有事情,然后它就会再次工作。

关于php - Laravel 9 未定义类 'MainController' 一旦取消注释 RouteServiceProvider 中的 Controller 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72009021/

相关文章:

php - 没有为 [sitemap] laravel 9 定义提示路径

Firefox 中的 php jquery 错误

javascript - laravel 中下拉菜单发生变化时显示数据

PHP - Apache - MySQL 服务器 | PHP - Apache - MySQL 服务器无法连接到主机

php - 使用类似于 HTTP_X_FORWARDED_FOR 的方法在 laravel 中获取用户 IP 地址

php - Laravel 多对多关系 5 个表

Laravel 9 路由问题返回 404 NOT FOUND

php - 如何将文件直接上传到Cloudinary而不先将其保存在公共(public)文件夹中

php - 我正在对 ajax 处理添加加载效果。它在 mozilla 中工作正常,但 css 在 chrome 中不起作用

php - 在 jQuery ajax 数据字符串中使用的字符串值的序列化函数