Skip to content

Domain wildcard group in routes and url generation for named routes #7366

@jan-j

Description

@jan-j

I have route group with domain wildcard. Something like this:

Route::group(
    [
        'domain' => '{subdomain}.domain.com',
    ],
    function ($router) {
        Route::get(
            '/',
            [
                'uses' => function ($subdomain) {
                    return route('subhome');
                },
                'as' => 'subhome'
            ]
        );
    }
);

Route is working well, catching only subdomain request. But there is a problem in url generation for named route. Above code will produce:

http://%7Bsubdomain%7D.domain.com

{subdomain} wildcard is not converted to current subdomain, and named routes are not usable. I found dirty solution to this:

Route::group(
    [
        'domain' => '{subdomain}.domain.com',
    ],
    function ($router) {
        Route::get(
            '/',
            [
                'uses' => function ($subdomain) use ($router) {
                    $route = $router->getCurrentRoute();
                    $action = $route->getAction();
                    $action['domain'] = $subdomain . '.domain.com';
                    $route->setAction($action);

                    return route('subhome');
                },
                'as' => 'subhome'
            ]
        );
    }
);

It is now outputting correct route url:

http://subdomain1.domain.com

This solution works, but it is a dirty one. It can be probably taken out from there and made into its own middleware or event handler class, but I'm wondering if there is, or should be any better solution?

EDIT

My solution is not quite right. Because you need to update all routes actions with correct subdomains. This probably can be done through RouteCollection class, but this is not optimal in case of performance. And ugly as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions