How to Get Http Hostname in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hello Dev,

This tutorial is focused on how to get http hostname in laravel. This article goes in detailed on how to get hostname in laravel. Here you will learn laravel request hostname. step by step explain laravel get hostname. So, let us see in detail an example.

In this example, we will use using getHost() or getHttpHost() request method to get hostname in laravel. we will see simple example with output.

1. getHost(): getHost() is used to retrieve the HTTP host from the "Host" header of the incoming request. The "Host" header is a part of the HTTP request headers sent by the client (e.g., a web browser) and specifies the hostname of the server to which the client is making the request.

It returns the host as a string, without the scheme (http or https) or any port information. If you want to get just the hostname, this method is useful.

2. getHttpHost(): getHttpHost() is also used to retrieve the HTTP host from the "Host" header of the incoming request, but it includes the scheme (http or https) and port information, if applicable.

It returns the host as a complete URL, which includes the scheme and port number. This method can be helpful when you need the complete URL, including the protocol and port.

Let's see the one by one example:

Example 1: Laravel Get Hostname using getHost()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$hostname = $request->getHost();

return "HTTP Hostname: " . $hostname;

}

}

Output:

HTTP Hostname: localhost

Example 2: Laravel Get Hostname using getHttpHost()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$hostname = $request->getHttpHost();

return "HTTP Hostname: " . $hostname;

}

}

Output:

HTTP Hostname: http://example.com:8080

I hope it can help you...

Tags :
Shares