Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 537
Stidges Avatar asked Oct 27 '25 10:10

Stidges


1 Answers

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');
    });
}
like image 86
Jeemusu Avatar answered Oct 28 '25 22:10

Jeemusu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!