How To Get HTTP Hostname In Laravel 10 Tutorial

Reading Time: 3 minutes
596 Views

In Laravel 10, getting the HTTP hostname is necessary for a variety of scenarios, including generating dynamic URLs, determining the current domain, and dealing with multi-domain applications. The HTTP hostname represents the domain name used to access the application.

Read More: How to Check If a File Exists in Laravel 10 Tutorial

In this detailed article, we will guide you through the process for getting the HTTP hostname in Laravel 10. We will investigate various techniques and approaches for dynamically retrieving the hostname, ensuring flexibility and compatibility across multiple contexts.

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Get HTTP Hostname Using Request Helper

Get HTTP Hostname in views or in controllers using request helper function –

$host = request()->getHttpHost();

request() is a helper function of laravel which you can use inside blade templates as well. Above code returns the application URL with port number.

If you are running your application at localhost then it will return output –

127.0.0.1:8000

Read More: Laravel 10 How To Change Name And From Address in Email

Get HTTP Host Using Request Helper

Get HTTP Host in views or in controllers using request helper function –

$host = request()->getHost();

Above code returns the application URL only.

If you are running your application at localhost then it will return output –

127.0.0.1

Get HTTP Hostname Using Request Object

The Request and it’s instance is available in controllers or any of classes only. You can import Request class via –

use Illuminate\Http\Request;

Get HTTP Hostname in controllers using request object –

//...

public function anyControllerMethod(Request $request) { 
    
     $hostname = $request->getHttpHost(); 

     $host = $request->getHost(); 
 
     print_r($hostname); 

     print_r($host); 
}

We hope this article helped you to How To Get HTTP Hostname In Laravel 10 Tutorial in a very detailed way.

Read More: Laravel 10 How To Add Image Into PDF Using DomPDF Library

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.