在此之后changes即 Laravel 5.2.31 及以上版本,app/Http/routes.php
中的所有路由都将归入 web 中间件组。
在 RouteServiceProvider.php
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
问题:
- 在没有
web
中间件的情况下定义一组路由的最简单/最好的方法是什么?
其中一个用例是,声明无 session 中间件的无状态 api 的路由,属于 web 组中间件
最佳答案
我解决这个问题的一种方法是编辑 app/Providers/RouteServiceProvider.php
并为其他组中间件(即 api)设置另一个路由文件
public function map(Router $router)
{
$this->mapWebRoutes($router);
$this->mapApiRoutes($router);
//
}
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
// Add this method and call it in map method.
protected function mapApiRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'api',
], function ($router) {
require app_path('Http/routes-api.php');
});
}
要验证结果,请在终端上运行 php artisan route:list
并检查路由中间件。
例如:
现在我有一些没有 web 中间件的路由,它在不同的文件中定义,稍后在 RouteServiceProvider 中调用
或
如果你喜欢旧的功能,你可以有这样的东西:
public function map(Router $router)
{
$this->mapWebRoutes($router);
$this->mapGeneralRoutes($router);
}
protected function mapGeneralRoutes(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes-general.php');
});
}
然后,在 routes-general.php
中,您可以像以前一样为不同的路由集设置多个中间件组
关于php - 在 Laravel >= 5.2.31 的路由中避免/删除网络中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37417593/