Laravel获取多域路由中的当前域 [英] Laravel get route current domain in multiple domains route
问题描述
我想阻止从列出的其他域访问我的某些应用程序路由,但列出的除外.使用以下代码成功:
I want to prevent access to some of my app routes from other domain except listed. It success using below code:
$loginRoutes = function() {
Route::get('/', 'HomeController@index')->name('home');
};
Route::domain('domain1.com')->group($loginRoutes);
Route::domain('domain2.com')->group($loginRoutes);
Route::domain('localhost')->group($loginRoutes);
但是问题是,当我调用 {{route('home')}}
时,URL始终成为routes.php的最后一行的域(上面的情况是http://localhost).如何将其添加到当前域?
But the problem is when I call {{route('home')}}
, the URL always becomes the domain at the last line of the routes.php(at above case is http://localhost ). How to make it to current domain?
我当前的解决方案:
if (isset($_SERVER["HTTP_HOST"]) && $_SERVER["HTTP_HOST"] == "domain1.com") {
Route::domain('domain1.com')->group($loginRoutes);
}elseif (isset($_SERVER["HTTP_HOST"]) && $_SERVER["HTTP_HOST"] == "domain2.com") {
Route::domain('domain2.com')->group($loginRoutes);
}
这是工作,但我认为它很脏.我有很多域/子域,还有路由.
It's work but I think it's dirty. I have a lot of domains/subdomain and also the routes too.
我直接需要路由解决方案,因为我有很多路由,如果我更新每个控制器,将花费很长时间.也许编辑路由提供者或laravel供应商代码也没问题.
I need solution on route directly, because I have a lot of routes, if I update each controller it's will take a long time. Maybe edit route provider or laravel vendor code is also no problem.
推荐答案
我也在使用PHP 7.3和Laravel 5.7我实际上在我的域中使用此路由.也许这与您要求的不完全相同,但是您可以尝试这样的操作
I am also using PHP 7.3 and Laravel 5.7 I actually use this routing for my domains. Maybe this is not exactly what you asked, but you can try something like this
// To get the routes from other domains
// Always add the new domains here
$loginRoutes = function() {
Route::get('/', 'HomeController@index')->name('home');
};
Route::group(array('domain' => 'domain1.com'), $loginRoutes);
Route::group(array('domain' => 'domain2.com'), $loginRoutes);
Route::group(array('domain' => 'domain3.com'), $loginRoutes);
如果要在域级别处理某些事情.在您的控制器(HomeController @ index)中,您可以获取当前域并执行所需的任何操作.为了获得确切的域,我使用了这样的方法:
If you want to handle something at the domain level. In your controller (HomeController@index), you can get the current domain and do whatever you want. To get exact domain I have used like this:
class HomeController extends Controller
{
public function index()
{
$domain = parse_url(request()->root())['host'];
if ($domain == 'domain1.com'){
// do something
}
...
}
...
}
这样,我可以为每个域处理不同的事情.
That way I can handle different things for each domain.
为了使其更加完整,我们可以从表/查询中获取域并动态创建路由.
$domains = Cache::get('partners')->where('status', '=', 'A')->where('domain', '<>', '')->all();
$loginRoutes = function() {
Route::get('/', 'HomeController@ index')->name('home');
};
foreach ($domains as $domain) {
Route::group(array('domain' => $domain->dominio_externo), $loginRoutes);
}
它一直在为我工作.希望对您有所帮助.
It has been working for me. I hope to help you.
这篇关于Laravel获取多域路由中的当前域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!