我全新安装了 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/