我可以在
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 文件工作吗?
我已经尝试/考虑过:
有什么想法吗?
更新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');
});
}
在您的
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
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
命令
另一种方法是将路由移动到文件夹并在其中循环,这样您就不必在添加新文件时不断更新提供程序。
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(function () {
foreach (glob(base_path('routes/api/*.php')) as $fileName) {
require $fileName;
}
});
对于 laravel 11 ,路由定制,在
bootstrap/app.php
有时您可能想要定义一个全新的文件来包含 应用程序路由的子集。为了实现这一点,您可以 为 withRouting 方法提供 then 闭包。在这个封闭范围内, 您可以注册您所需的任何其他路线 应用
use Illuminate\Support\Facades\Route;
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
then: function () {
Route::middleware('api')
->prefix('webhooks')
->name('webhooks.')
->group(base_path('routes/webhooks.php'));
},
)
例如,如果我们在
test.php
和 admin.php
中创建
routes/test.php
和
routes/admin.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
then: function () {
Route::prefix('test')->name('test.')->group(base_path('routes/test.php'));
Route::prefix('admin')->name('admin.')->group(base_path('routes/admin.php'));
},
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();