【问题标题】:Laravel nested route group inverse middlewareLaravel 嵌套路由组反向中间件
【发布时间】:2015-08-01 16:26:29
【问题描述】:

我有一个相当复杂的应用程序,它使用了自定义身份验证中间件。我有一个这样的路由组:

Route::group(['prefix' => 'auth', 'middleware' => 'auth'], function() {

    Route::get('/', function() {

        echo 'private';
    });

    Route::group(['prefix' => 'public'], function() {

        Route::get('/', function() {

            echo 'public';
        });
    })
});

现在auth 中间件将重定向所有未通过身份验证的请求。带有auth 前缀的主组已通过身份验证。但是,即使用户未通过身份验证,我也希望可以访问组 public

所以:

http://example.com/auth < must be authenticated
http://example.com/auth/some-sub-page < must be authenticated
http://example.com/auth/public < no need for authentication

那么有没有办法将'remove-middleware' =&gt; 'auth' 之类的内容添加到带有public 前缀的嵌套组中?还是我必须重组我的路线组?

【问题讨论】:

    标签: php laravel laravel-5 laravel-routing middleware


    【解决方案1】:

    为什么不将 auth 中间件包裹在非公共路由周围?

    Route::group(['prefix' => 'auth'], function() {
    
        // routes requiring auth
        Route::group(['middleware' => 'auth']) {
    
            Route::get('/', function() {
    
                echo 'private';
            });
    
        }
    
        // other routes
        Route::group(['prefix' => 'public'], function() {
    
            Route::get('/', function() {
    
                echo 'public';
            });
    
        });
    });
    

    可能有一种方法可以做一个“删除中间件”类型的中间件,但这可能会变得混乱。这似乎是最干净的解决方案。

    【讨论】:

      【解决方案2】:

      您可以在您的路线上使用withoutMiddleware 方法。

      Route::get('/example')-&gt;withoutMiddleware('auth')

      你也可以在Route::group上使用withoutMiddleware

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-27
        • 2018-09-10
        • 2016-06-20
        • 2020-09-04
        • 2015-11-17
        • 2019-02-18
        • 1970-01-01
        • 2016-12-09
        相关资源
        最近更新 更多