简体   繁体   English

Laravel:在Route :: group()闭包中获取路由参数

[英]Laravel: Getting Route Parameters in Route::group() Closure

I have an app running on Laravel 4.2, and I am trying to implement a somewhat complex routing mechanism. 我有一个在Laravel 4.2上运行的应用程序,并且我正在尝试实现某种复杂的路由机制。 I have a route group set up using: 我使用以下方法设置了路由组:

Route::group(['domain' => '{wildcard}.example.com'], $closure);

I need to be able to check the $wildcard parameter in the closure for the group -- meaning before the request gets passed to the controller (I need to defined Route::get() and Route::post() depending on the subdomain). 我需要能够检查该组闭包中的$ wildcard参数-这意味着在将请求传递给控制器​​之前(我需要根据子域定义Route::get()Route::post() )。

An example of what I'd like to do is as follows: 我想做的一个例子如下:

Route::group(['domain' => '{wildcard}.example.com', function ($wildcard) {
        if ( $wildcard == 'subdomain1' ) {
            Route::get('route1', 'Subdomain1Controller@getRoute1');
            Route::get('route2', 'Subdomain1Controller@getRoute2');
        } else if ( $wildcard == 'subdomain2' ) {
            Route::get('route1', 'Subdomain2Controller@getRoute1');
            Route::get('route2', 'Subdomain2Controller@getRoute2');
        }
    }
);

Of course, the above does not work. 当然,以上方法不起作用。 The only parameter passed into a Route::group() closure is an instance of Router , not the parameters defined in the array. 传递给Route::group()闭包的唯一参数是Router的实例,而不是数组中定义的参数。 However, there must be a way to access those parameters -- I know for a fact that I've done it before, I just don't remember how (and can't find the solution anywhere online). 但是, 必须有一种访问这些参数的方法-我知道我之前已经做过,但我只是不记得怎么做(并且无法在线找到解决方案)。

I know I can always use PHP's lower-level methods to retrieve the URL, explode() it, and check the subdomain that way. 我知道我总是可以使用PHP的较低层方法来检索URL,对其进行explode()并以这种方式检查子域。 But I've done it before using Laravel's methods, and if possible, I'd prefer to do it that way (to keep things clean and consistent) 但是我在使用Laravel的方法之前就已经做到了,如果可能的话,我宁愿那样做(保持事物的清洁和一致)

Does anyone else know the solution? 还有其他人知道解决方案吗? Thanks in advance! 提前致谢!

Use the Route::input() function: 使用Route::input()函数:

 Route::group(['domain' => '{wildcard}.example.com', function ($wildcard) use ($wildcard) {
        if ( Route::input('wildcard') === 'subdomain1' ) {
            Route::get('route1', 'Subdomain1Controller@getRoute1');
            Route::get('route2', 'Subdomain1Controller@getRoute2');
        } else {
            Route::get('route1', 'Subdomain2Controller@getRoute1');
            Route::get('route2', 'Subdomain2Controller@getRoute2');
        }
    }
);

See "Accessing A Route Parameter Value" in the docs . 请参阅docs中的 “访问路由参数值”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM