How do you get the HTTP host with Laravel 5

65,100

Solution 1

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!

Solution 2

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

Solution 3

laravel 5.6 and above

request()->getSchemeAndHttpHost()

Example of use in blade :

{{ request()->getSchemeAndHttpHost() }}

Solution 4

You can use request()->url();

Also you can dump the complete request()->headers();

And see if that data is useful for you.

Share:
65,100
Sean the Bean
Author by

Sean the Bean

Web developer at MyFarms, LLC. Experienced in JavaScript, jQuery, CoffeeScript, CSS, Bootstrap, TaffyDB, PHP, Laravel, PostgreSQL, MySQL, ASP.NET, C#, and C++. Used more languages than I can count on both hands... in binary.

Updated on July 09, 2022

Comments

  • Sean the Bean
    Sean the Bean almost 2 years

    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?