这是我的控制器:

<?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中,在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 9中,不需要在RouteServiceProvider中添加命名空间。

而不是

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

use

Route::resource('tickets', TicketController::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'));
    });
}

Laravel 8文档实际上比这里的任何答案都更简洁和清楚地回答了这个问题:

路由命名空间更新

在Laravel之前的版本中,RouteServiceProvider包含一个$namespace属性。此属性的值将自动添加到控制器路由定义的前缀,并调用动作助手/ URL::action方法。在Laravel 8。X,此属性默认为空。这意味着Laravel不会自动添加名称空间前缀。因此,在新的Laravel 8。x应用程序,控制器路由定义应该使用标准的PHP可调用语法定义:

use App\Http\Controllers\UserController;

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

对动作相关方法的调用应该使用相同的可调用语法:

action([UserController::class, 'index']);

return Redirect::action([UserController::class, 'index']);

如果你喜欢Laravel 7。x风格的控制器路由前缀,你可以简单地将$namespace属性添加到应用程序的RouteServiceProvider中。

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

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

应改为:

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

在Laravel 8中,你可以这样使用它:

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