【问题标题】:Laravel new package not finding correct controller pathLaravel 新包找不到正确的控制器路径
【发布时间】:2019-09-18 20:12:48
【问题描述】:

我使用 Laravel 5.6.39 安装了一个名为 Mercurius Messenger 的包

这个包通过composer安装了它的所有资产,所以我可以在/vendor/launcher/中查看它们

在他们的仓库中,他们有一个路由文件。

Route::group([
    'as'         => 'mercurius.',
    'namespace'  => '\Launcher\Mercurius\Http\Controllers',
    'middleware' => [
        // 'Mercurius',
        'web',
        'auth',
    ],
], function () {
    // Mercurius home
    Route::get('/messages', ['as' => 'home', 'uses' => 'MessagesController@index']);
    // User Profile
    Route::get('/profile/refresh', 'ProfileController@refresh');
    Route::get('/profile/notifications', 'ProfileController@notifications');
});

上面添加了控制器的命名空间:

\Launcher\Mercurius\Http\Controllers

当我尝试访问这些路线之一时,我收到此错误:

"Class App\Http\Controllers\Launcher\Mercurius\Http\Controllers\MessagesController does not exist"

这显然是将命名空间添加到我的 App\Http\Controllers 的当前命名空间中,有没有办法解决这个问题?还是我必须将所有相关文件复制到我的项目中并整理它们应该去哪里?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您绝对不需要(或不想)将供应商文件复制到您的项目中。

    最简单的选择可能是从路由组中删除namespace 属性,并在定义路由时使用完整的命名空间。

    Route::get('/messages', ['as' => 'home', 'uses' => '\Launcher\Mercurius\Http\Controllers\MessagesController@index']);
    Route::get('/profile/refresh', '\Launcher\Mercurius\Http\Controllers\ProfileController@refresh');
    Route::get('/profile/notifications', '\Launcher\Mercurius\Http\Controllers\ProfileController@notifications');
    

    或者,您可以创建一个新的路由文件(例如,mercurius.php)并将其映射到您的 RouteServiceProvider.php 中并使用正确的命名空间。

    public function map()
    {
        // ... existing route groups
    
        $this->mapMercuriusRoutes();
    }
    
    protected function mapMercuriusRoutes()
    {
        Route::middleware(['web','auth','Mercurius'])
             ->namespace('\Launcher\Mercurius\Http\Controllers')
             ->group(base_path('routes/mercurius.php'));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2014-01-23
      • 1970-01-01
      • 2016-02-29
      相关资源
      最近更新 更多