[英]Get the subdomain in a subdomain-route (Laravel)
我正在構建一個子域指向用戶的應用程序。 如何在路由之外的其他地方獲取地址的子域部分?
Route::group(array('domain' => '{subdomain}.project.dev'), function() {
Route::get('foo', function($subdomain) {
// Here I can access $subdomain
});
// How can I get $subdomain here?
});
不過,我已經建立了一個混亂的解決方法:
Route::bind('subdomain', function($subdomain) {
// Use IoC to store the variable for use anywhere
App::bindIf('subdomain', function($app) use($subdomain) {
return $subdomain;
});
// We are technically replacing the subdomain-variable
// However, we don't need to change it
return $subdomain;
});
我想在路由之外使用變量的原因是基於該變量建立數據庫連接。
$subdomain
是在實際的Route
回調中注入的,它在group
閉包中是未定義的,因為Request
還沒有被解析。
我不明白為什么你需要在組閉包內使用它,但在實際的Route
回調之外。
如果您希望在解析Request
在任何地方都可以使用它,您可以設置一個后過濾器來存儲$subdomain
值:
Config::set('request.subdomain', Route::getCurrentRoute()->getParameter('subdomain'));
更新:應用組過濾器來設置數據庫連接。
Route::filter('set_subdomain_db', function($route, $request)
{
//set your $db here based on $route or $request information.
//set it to a config for example, so it si available in all
//the routes this filter is applied to
Config::set('request.subdomain', 'subdomain_here');
Config::set('request.db', 'db_conn_here');
});
Route::group(array(
'domain' => '{subdomain}.project.dev',
'before' => 'set_subdomain_db'
), function() {
Route::get('foo', function() {
Config::get('request.subdomain');
});
Route::get('bar', function() {
Config::get('request.subdomain');
Config::get('request.db');
});
});
以上不適用於 Laravel 5.4 或 5.6。 請測試這個:
$subdomain = array_first(explode('.', request()->getHost()));
使用宏的方式:
Request::macro('subdomain', function () {
return current(explode('.', $this->getHost()));
});
現在你可以使用它:
$request->subdomain();
在路由調用中
$route = Route::getCurrentRoute();
現在您應該可以訪問該路線的所有內容。 IE
$route = Route::getCurrentRoute();
$subdomain = $route->getParameter('subdomain');
像這樣
Route::getCurrentRoute()->subdomain
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.