How do you get the HTTP host with Laravel 5
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
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
It took a bit of digging through the source to find this, so I hope it helps!