这是我的控制器:

<?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):

php artisan route:clear

其他回答

在Laravel 8中,默认是删除名称空间前缀,所以你可以在Laravel 7中设置旧的方式:

在RouteServiceProvider.php中添加这个变量:

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

并更新启动方法:

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'));
    });
}

如果你想继续使用原来的自动前缀控制器路由,你可以简单地在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'));
    });
}

当我安装Laravel 8.27.0版本时,我得到了同样的错误: 错误如下:

但是当我看到我的app/Providers/RouteServiceProvider.php文件时,我的引导方法中有名称空间。然后我只是取消注释this => protected $namespace = '应用\\Http\\控制器';。

现在我的项目正在工作。

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

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

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

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

例如:

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