2015-08-23 57 views
8

我剛開始學習Laravel 5並嘗試創建多語言網站,並且想要爲該語言使用不同的域,因此en.example.app指向英文版,es .example.app到西班牙語等。我使用路由組,下面是我的代碼。Laravel 5,子域路由,帶有可選參數

Route::group(['domain' => '{domain}.example.app'], function() { 
    Route::get('/', function() { 
     return view('index'); 
    }); 
    Route::get('test', function(){ 
     return view('index'); 
    }); 
}); 

它適用於除example.app以外的所有域。不幸的是,可選參數{domain?}不適用於子域名,我不想重複這樣的路由。

Route::get('/', function() { 
    return view('index'); 
}); 
Route::get('test', function(){ 
    return view('index'); 
}); 

Route::group(['domain' => '{domain}.example.app'], function() { 
    Route::get('/', function() { 
     return view('index'); 
    }); 
    Route::get('test', function(){ 
     return view('index'); 
    }); 
}); 

請問有人請告知如何避免這種重複?

+0

如果用戶訪問example.app什麼語言他得到英文版或自定義網站與不同的顯示 –

回答

2

那監守的{domain}.example.app需要.example.app

您可以刪除.domain參數添加contraint它有atmost 1 .

因此,代碼會看起來像

Route::group(['domain' => '{domain}example.app'], function($group) { 
    Route::get('/', function ($domain) { 
     //code 
    }) ; 
    // more routes 

    foreach($group->getRoutes() as $route){ 
     $route->where('domain', '[a-z]+\.{0,1}'); 
    } 

}); 

附: :我不知道我的正則表達式是否正確。

1

對於沒有子域名的HTTP請求,您的選項可能是路由重複或服務器級別重定向。

簡單的選擇只是將example.app轉發到www.example.app

3

A MiddleWare幫了我。

Route::group(array('middleware' => 'resolve_domain'), function() { 
    Route::get('/', '[email protected]'); 
}); 

而且在中間件 -

public function handle($request, Closure $next) 
{ 
    $params = explode('.', $request->getHost()); 
    $sub_domains = config('admin_configs.editions'); // Predefined sub-domain 
    $edition = false; 
    if(!empty($params[0]) && in_array($params[0], $sub_domains, true)) { 
     $edition = $params[0]; 
    } 
    define('DOMAIN_EDITION', $edition); // Set constant to be used. 

    return $next($request); 
} 
2

您可以創建一個名爲app-routes.php文件,它包含的所有路由,然後在實際routes.php文件

Route::group(['domain' => '{domain}.example.app'], function() { 
    include('app-routes.php'); 
}); 

Route::group(['domain' => 'example.app'], function() { 
    include('app-routes.php'); 
}); 
+0

偉大的1,但你試過嗎?如何將域設置爲一些常量? –

+0

我試過了,但我無法從example.app正確地鏈接到subdomain.example.app ...對此有任何想法? @ J-戴維斯。我嘗試了{{URL :: route('home',array('subdomain'=>'johndoe'))}} – AceKYD

1
Route::group(['domain' => '{domain}.example.app'], function() { 

}); 

Route::group(['domain' => 'example.app'], function() { 

}); 

這模式是好的,但如果你w螞蟻使用不同的語言添加本地化文件