这是我的控制器:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    public function register(Request $request)
    {
        dd('aa');
    }
}

如截图所示,类存在并且在正确的位置:

我的api.php路由:

Route::get('register', 'Api\RegisterController@register');

当我使用Postman命中我的寄存器路径时,它给了我以下错误:

目标类[Api\RegisterController]不存在。

我该怎么解决呢?


多亏了这些答案,我才得以修复它。我决定对这个路由使用完全限定类名,但是答案中描述了其他选项。

Route::get('register', 'App\Http\Controllers\Api\RegisterController@register');

当前回答

在Laravel 9中,不需要在RouteServiceProvider中添加命名空间。

而不是

Route::resource('tickets', 'TicketController');

use

Route::resource('tickets', TicketController::class);

其他回答

如果你想继续使用原来的自动前缀控制器路由,你可以简单地在RouteServiceProvider中设置$namespace属性的值,并在引导方法中更新路由注册以使用$namespace属性:

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

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

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

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

我犯了这个错误:

(阐明\合同\ \ BindingResolutionException容器 目标类[App\Http\Controllers\ControllerFileName]不存在。

解决方案:

检查一下你的类名。它应该与您的文件名完全相同。

确保在路由中使用了正确的文件名。

例如:

如果你的控制器文件名为User.php,请确保你引用的是User而不是UserController。

只需取消注释下面这行来自RouteServiceProvider(如果不存在,则添加它):

protected $namespace = 'App\\Http\\Controllers';

当我传递null到中间件函数时,它发生在我身上:

Route::middleware(null)->group(function () {
    Route::get('/some-path', [SomeController::class, 'search']);
});

为中间件传递[]无效。或者如果不使用中间件,可能只是删除中间件调用:D