这是我的控制器:

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

当前回答

是的,检查路由文件夹中的web.php是否使用了Controller类。

use App\Http\Controllers\<name of controlelr class>

其他回答

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

我犯了这个错误:

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

解决方案:

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

我试了所有的方法,都没用,直到我第二次尝试 重新启动服务器

php artisan cache:clear
php artisan optimize

php artisan route:list

在新安装的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文件中,让它以旧的方式运行。

是的,在Laravel 8中确实发生了这个错误。 在尝试了许多解决方案后,我得到了这个完美的解决方案。 只要按照步骤做……

案例1

我们可以在api.php和web.php文件中更改如下。 目前我们编写语法的方式是

Route::get('login', 'LoginController@login');

应该改为:

Route::get('login', [LoginController::class, 'login']);

案例2

首先打开这个文件:app > Providers > RouteServiceProvider.php 在该文件中替换该行 Protected $namespace = null;用protected $namespace = '应用程序\Http\控制器'; 然后添加line ->命名空间($this->命名空间)如图…