简体   繁体   中英

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. 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).

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. 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. 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)

Does anyone else know the solution? Thanks in advance!

Use the Route::input() function:

 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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