Reputation: 5392
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?
Upvotes: 51
Views: 99304
Reputation: 5392
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
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
Upvotes: 114
Reputation: 7730
request()->getSchemeAndHttpHost()
Example of use in blade :
{{ request()->getSchemeAndHttpHost() }}
Upvotes: 13
Reputation: 406
You can use request()->url();
Also you can dump the complete request()->headers();
And see if that data is useful for you.
Upvotes: 2
Reputation: 5783
There two ways, so be careful:
<?php
$host = request()->getHttpHost(); // With port if there is. Eg: mydomain.com:81
$host = request()->getHost(); // Only hostname Eg: mydomain.com
Upvotes: 30