php - 在 Laravel >= 5.2.31 的路由中避免/删除网络中间件

标签 php laravel

在此之后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');
    });
}

问题:

  1. 在没有 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 并检查路由中间件。

例如:

Now I have some route without web middleware which is defined in different file which later called in RouteServiceProvider

现在我有一些没有 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/

相关文章:

php - openssl 和 php SHA512 的区别

php - 试图理解 php mysqli multi_query

javascript - Like Unlike 切换按钮与 jQuery 的 AJAX

php - Composer : Specify autoload_files require order

php - Input::file() 返回 null Laravel

php - 在 PHP 中将一些新数据添加到数组中

php - 如何以最低复杂度且只有一次返回来处理错误

c# - 将空数组序列化和反序列化为字典/对象

php - Laravel 背包 $guarded 字段处理

php - Laravel 嵌套数组的类型转换