这是我的控制器:

<?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 8中,指定路由的方式已经改变:

Route::resource('homes', HomeController::class)->names('home.index');

其他回答

对于解决方案,只需取消第29行注释:

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

在app\Providers\RouteServiceProvider.php文件中。

只需取消第29行注释

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

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

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

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

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

在新安装的Laravel 8中,在App/Providers/RouteServices.php文件中:

 /*
 * The path to the "home" route for your application.
 *
 * This is used by Laravel authentication to redirect users after login.
 *
 * @var string
 */
public const HOME = '/home';

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

取消注释行

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

这应该能帮你用传统的方式管理拉拉维尔。

如果你从Laravel的低版本升级到8版本,那么你可能不得不隐式地添加line

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

在RouteServices.php文件中,让它以旧的方式运行。

我在运行php artisan route:list时遇到了同样的错误。在我的情况下,我已经删除了追索权控制器,但路由仍然被定义。我必须确保在routes/web.php中注释掉了有问题的类。