这是我的控制器:

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

当前回答

在app/Providers文件夹中,文件RouteServiceProvider.php,将受保护的$namespace变量更改为

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

这将在保存时自动注释变量。

其他回答

如果你正在使用Laravel 8,只需复制并粘贴我的代码:

use App\Http\Controllers\UserController;

Route::get('/user', [UserController::class, 'index']);

Laravel 8更新了RouteServiceProvider,它用字符串语法影响路由。你可以像之前的答案一样改变它,但推荐的方法是使用动作语法,而不是使用字符串语法的路由:

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

应改为:

Route::get('register', [RegisterController::class, 'register']);

如果你想继续使用原来的自动前缀控制器路由,你可以简单地在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中,你可以这样使用它:

Route::group(['namespace'=>'App\Http\Controllers', 'prefix'=>'admin',
 'as'=>'admin.', 'middleware' => ['auth:sanctum', 'verified']], function()
{
    Route::resource('/dashboard', 'DashboardController')->only([
        'index'
    ]);
});

在我的例子中,我也犯了同样的错误,因为我忘记将路径中控制器的第一个字母大写。

所以我改变了

使用App\Http\controllers\HomeController;

:

使用App\Http\Controllers\HomeController;