How To Get HTTP Hostname In Laravel 9 Tutorial

Reading Time: 3 minutes
2,924 Views

Inside this article you will get the idea to get HTTP Hostname in Laravel 9. This article contains the classified information about the Hostname in laravel 9.

If you are wondering to find the same topic then you are at right place to learn and get the concept of http hostname in laravel 9. This is actually not laravel version specific even you can use it with any version.

Hostname refers to the name of domain or subdomain from where HTTP request has been initiated. By using request object or request helper function we can get the information of HTTP hostname etc.

Learn More –

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

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 9 Tutorial in a very detailed way.

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.