如何使用Laravel 5获取HTTP主机 [英] How do you get the HTTP host with Laravel 5

查看:352
本文介绍了如何使用Laravel 5获取HTTP主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Laravel 5从HTTP请求中获取主机名,包括子域(例如dev.site.com).我在文档中找不到任何相关内容,但是我认为这应该很简单.有人知道该怎么做吗?

I'm trying to get the hostname from an HTTP request using Laravel 5, including the subdomain (e.g., dev.site.com). I can't find anything about this in the docs, but I would think that should be pretty simple. Anyone know how to do this?

推荐答案

好消息!事实证明,这确实很容易,尽管Laravel的Request文档有点缺乏(我想要的方法是从

Good news! It turns out this is actually pretty easy, although Laravel's Request documentation is a bit lacking (the method I wanted is inherited from Symfony's Request class). If you're in a controller method, you can inject the request object, which has a getHttpHost method. This provides exactly what I was looking for:

public function anyMyRoute(Request $request) {
    $host = $request->getHttpHost(); // returns dev.site.com
}

在代码的任何其他位置,您仍然可以使用 辅助功能,因此如下所示:

From anywhere else in your code, you can still access the request object using the request helper function, so this would look like:

$host = request()->getHttpHost(); // returns dev.site.com

如果要在URL中包含http/https部分,则可以直接使用getSchemeAndHttpHost方法:

If you want to include the http/https part of the URL, you can just use the getSchemeAndHttpHost method instead:

$host = $request->getSchemeAndHttpHost(); // returns https://dev.site.com

需要花一些时间来寻找源代码,所以希望对您有所帮助!

It took a bit of digging through the source to find this, so I hope it helps!

这篇关于如何使用Laravel 5获取HTTP主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆