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?
The “path” method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which matches the particular pattern specified in the argument of the method. To get the full URL, we can use the url method.
To access a named route, you could use the following: echo route('posts'); This would check your routes file and return the correct route with name posts , e.g. https://yourdomain.com/posts . Alternatively to the url() helper, you could use the URL facade.
Introduction. Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With