Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the HTTP host with Laravel 5

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?

like image 319
Sean the Bean Avatar asked Oct 03 '16 15:10

Sean the Bean


People also ask

How can you retrieve the full URL for the incoming request laravel?

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.

How do I find base URL in laravel?

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.

What is HTTP request in laravel?

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.


2 Answers

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!

like image 197
Sean the Bean Avatar answered Sep 24 '22 00:09

Sean the Bean


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 
like image 28
insign Avatar answered Sep 21 '22 00:09

insign