Stidges
Stidges

Reputation: 141

Laravel: Optional route prefix parameter

I'm currently working on a multi-site application (one codebase for multiple (sub)sites) and I would love to leverage route caching, but currently I'm hardcoding a prefix instead of dynamically determining it.

When trying to do this I'm running into an issue which I've illustrated below:

Route::group(['prefix' => '{subsite}', 'subdomain' => '{site}.domain.tld'], function () {
    Route::get('blog', 'BlogController@index')->name('blog.index');
});

When accessing a subsite like http://sitename.domain.tld/subsitename/blog this all works fine, but it doesn't work anymore when not accessing a subsite like http://sitename.domain.tld/blog, as it will now think that the prefix is 'blog'.

Is there any way to allow the 'subsite' parameter to be empty or skipped?

Thanks!

Upvotes: 4

Views: 2943

Answers (1)

Jeemusu
Jeemusu

Reputation: 10533

As far as I know there isn't anything in the current routing system that would allow you to solve your problem with a single route group.

While this doesn't answer your specific question, I can think of two ways that you could implement your expected behaviour.

1. Duplicate the route group

Route::group(['subdomain' => '{site}.domain.tld'], function () {
    Route::get('blog', 'BlogController@index')->name('blog.index');
});

Route::group(['prefix' => '{subsite}', 'subdomain' => '{site}.domain.tld'], function () {
    Route::get('blog', 'BlogController@index')->name('blog.index');
});

2. Loop through an array of expected prefixes.

$prefixes = ['', 'subsiteone', 'subsitetwo'];

foreach($prefixes as $prefix) {
    Route::group(['prefix' => $prefix, 'subdomain' => '{site}.domain.tld'], function () {
        Route::get('blog', 'BlogController@index')->name('blog.index');
    });
}

Upvotes: 3

Related Questions