【问题标题】:Adding more than 1 route file to laravel?向laravel添加超过1个路由文件?
【发布时间】:2021-09-28 13:29:45
【问题描述】:

我可以在RouteServiceProvider.php看到这个:

Route::prefix('api')
      ->middleware('api')
      ->namespace($this->namespace)
      ->group(base_path('routes/api.php'));

  Route::middleware('web')
      ->namespace($this->namespace)
      ->group(base_path('routes/web.php'));

但是当我尝试添加一个时:

  Route::middleware('web')
      ->namespace($this->namespace)
      ->group(base_path('themes/myTheme/web.php'));

然后它不会拾取第二个web.php 文件。但是如果我删除了第一个 web.php 引用,那么第二个引用就会被拾取。所以看起来 Laravel 只想要一个web.php。但是,即使这样也行不通:

  Route::middleware('myTheme')
      ->namespace($this->namespace)
      ->group(base_path('themes/myTheme/web.php'));

有没有办法让第二个 web.php 文件工作?

我已经尝试/考虑过:

  • 从主 web.php 文件中包含 web.php 文件的解决方法。但是,如果路线提供者处理它,我会更喜欢它。

有什么想法吗?

更新 1

我尝试了this,但它似乎不适用于 Laravel 8:

protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('api')
         ->namespace($this->namespace)
         ->group(function ($router) {
            require base_path('routes/admin.php');
            require base_path('routes/category.php');
        });
}

【问题讨论】:

  • 我在路由文件夹中创建了一个名为 test 的子文件夹,并在其中创建了一个 web.php 文件,对我来说这是工作 routes/test/web.php。您确定您的文件位于themes/myTheme/web.php。我还在test/web.php 创建了一个名为 test 的子文件夹(所以不在路由文件夹中),这也对我有用...
  • 是的,我知道它在正确的位置,因为如果我删除前一个它就可以工作。但另一条路线不在 /routes 中。它实际上在 /storage/sites/mysite/routes/web.php 中。如果它与它有任何关系会很奇怪。
  • @OMiShah 我想我可能会走那条路。斯库斯双关语。
  • @coderama 嗯,这可能与它有关,我的意思是我只能通过请求访问我存储中的项目。所以你的文件可能被隐藏了。

标签: laravel laravel-routing


【解决方案1】:
  Route::prefix('api')
      ->middleware('api')
      ->namespace($this->namespace)
      ->group(base_path('routes/api.php'));

  Route::middleware('web')
      ->namespace($this->namespace)
      ->group(base_path('routes/web.php'));

  Route::middleware('web')
      ->namespace($this->namespace)
      ->group(base_path('storage/routes/web2.php')); // 'themes/myTheme/web.php' in your case

这会起作用,但不要忘记在更改后运行php artisan route:cache 命令

【讨论】:

  • 不。不想工作。我会多弄一点。如果它对你有用,我显然做错了什么。
【解决方案2】:

在您的RouteServiceprovider.php 文件中修改以下部分:

Route::middleware('web')
      ->namespace($this->namespace)
      ->group(base_path('routes/web.php'));

并将其设为:

Route::middleware('web')
      ->namespace($this->namespace)
      ->group(function ($router) {
            require base_path('routes/web.php');
            require base_path('routes/test.php'); // replace the route file path
      });

然后确保使用以下命令清除缓存的路由:

php artisan route:clear

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-08
    • 2014-03-19
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多