Laravel: optional route prefix parameter
I am currently working on a multi-site application (one codebase for multiple (sub) sites) and I would like to use route caching, but I am currently hard-coding the prefix instead of dynamically defining it.
While trying to do this, I ran into the problem I illustrated below:
Route::group(['prefix' => '{subsite}', 'subdomain' => '{site}.domain.tld'], function () {
Route::get('blog', 'BlogController@index')->name('blog.index');
});
When accessing a child site like this http://sitename.domain.tld/subsitename/blog
, everything works fine, but it no longer works when it does not have access to the sub site, for example http://sitename.domain.tld/blog
, since it will now assume the prefix is "blog".
Is there a way to allow the "subsite" parameter to be empty or missing?
Thank!
source to share
As far as I know, there is nothing in the current routing system that would solve your problem with a single route group.
Until this answers your specific question, I can think of two ways to implement your expected behavior.
1. Duplicate 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. Scroll through the 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');
});
}
source to share