"Target class [Modules\Admins\Controllers\AdminController] does not exist."

"Target class [Modules\\Admins\\Controllers\\AdminController] does not exist."

我正在使用 Laravel 8 开发电子商务网站,我尝试更改 Laravel 文件夹结构 我已将 views 文件夹放入新路径 modules/admins 工作正常,我还在 modules/admins 路径中创建了一个模型文件夹,工作正常,但是,我遇到了问题控制器文件夹。

我仍然有 app/http/controllers/Controller.php,但现在我在 modules 文件夹中创建了一个名为 Controllers 的文件夹,我在其中有一个名为 AdminController

的控制器

错误信息:“目标class[Modules\Admins\Controllers\AdminController]不存在。”

项目结构 enter image description here

AdminController 文件


namespace Modules\Admins\Controllers;

use App\Http\Controllers\BaseController;
use App\Http\Traits\ApiDesignTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\{
    Hash, Validator
};
class AdminController extends BaseController
{
    public function test()
    {
        return true;
    }
}

route.php

use Illuminate\Support\Facades\Route;
use Modules\Admins\Controllers\AdminController;

Route::post('/test',  [AdminController::class, 'test']);

BaseController.php


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;


class BaseController extends Controller
{

}

Controller.php


namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

因为您定义的命名空间在应用之外,您应该自动加载它到您的composer.json文件中。

"autoload": {
    "psr-4": {
        "App\": "app/",
        "Database\Factories\": "database/factories/",
        "Database\Seeders\": "database/seeders/",
        "Modules\": "Modules/"
    }
},

然后 运行 composer dump-autoload 它应该可以正常工作。

您需要在路由服务提供者中更改路由文件的命名空间class 在 app/Providers/RouteServiceProvider.php 您需要编辑引导功能

/**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('web')
                ->namespace('Modules\Admins\Controllers')
                ->group(base_path('routes/route.php'));
        });
    }

在你的route.php中你可以这样做

Route::post('/test',  'AdminController@test');

如果您不想编辑服务提供商

Route::namespace('Modules\Admins\Controllers')->group(function () {
    Route::post('/test', 'AdminController@test');
});