【问题标题】:Middleware not working when created route from routeserviceprovider in laravel从 laravel 中的 routeserviceprovider 创建路由时中间件不起作用
【发布时间】:2020-11-17 15:21:30
【问题描述】:

从路由服务创建路由文件提供并分配中间件“admin.auth”,这个中间件在 web.php 中工作,提供管理员用户的基本信息,但从 custom.php 它返回 auth false。 admin.auth 如何从路由服务提供商那里工作

 protected function mapWebRoutes2()
    {
        Route::group([
            'namespace' => $this->namespace,
            'prefix' => 'custom',
            'middleware' => 'admin.auth'
        ], function ($router) {

            require base_path('routes/custom.php');
        });
    }

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    尝试复制现有的 api 路由示例。在您的示例中,例如:

    /**
     * Define the "custom" routes for the application.
     *
     * @return void
     */
    protected function mapWebRoutes2()
    {
        Route::prefix('custom')
            ->middleware(['admin.auth'])
            ->namespace($this->namespace)
            ->group(base_path('routes/custom.php'));
    }
    

    【讨论】:

    • 如果对您有帮助,请随时接受答案。 :) 总是选择Occam's razor。在文件本身中看到的只是复制和使用。 #SOreadytohelp
    • 这种方法不适用。如果我在 web.php 中添加文件以制作不同的文件来路由它的工作需要 DIR 。 '/afirmate.php';
    • 你为什么要这样做?在routes 目录位置创建您需要的文件。然后你可以在RouteServiceProvider 中添加所有这些。问题解决了。我多次以这种方式使用它,它工作得很好,而且它很好地分离和解耦。
    • 我这样放这里失败了?
    【解决方案2】:

    确保包含web 中间件,否则默认身份验证将不起作用,因为会话等未启动:

    protected function mapWebRoutes2()
    {
        Route::group([
            'namespace' => $this->namespace,
            'prefix' => 'custom',
            'middleware' => ['web', 'admin.auth']
        ], function () {
            require base_path('routes/custom.php');
        });
    }
    

    或更短:

    protected function mapWebRoutes2()
    {
        Route::prefix('custom')
            ->middleware(['web', 'admin.auth'])
            ->namespace($this->namespace)
            ->group(base_path('routes/custom.php'));
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 2018-07-21
      • 2020-08-30
      • 2018-05-11
      • 2018-10-25
      • 1970-01-01
      • 2017-11-09
      • 2019-03-10
      • 2016-07-09
      相关资源
      最近更新 更多