How to get Base URL in Laravel - Tutorial

INTRODUCTION
This short tutorial talks about quick way to access site's base url quickly so that you can refer to it anywhere
ABOUT THE AUTHOR
Kaustubh has been coding with Laravel for a few years now and aims to help newbie Laravel programmers get started with Laravel framework.
Kaustubh Katdare
Kaustubh Katdare
CEO @ CrazyEngineers, TEDx Speaker, Guitarist

Let's explore quick ways to get the site's base URL in Laravel. I had someone ask me how to do it in Laravel, because other frameworks like Codeigniter offer a quick helper function to do it:  base_url(); 

Thankfully, Laravel makes it super easy to get base URL as well as build URLs from base. In order to get the base URL in Laravel, use the URL facade:

URL::to('/');

This will output the link to base: aka say http://site.dev/

Thankfully, there is a simple helper function that does the job if you do not wish to use URL facade -

url('/');

That simple function will output the base URL of your site. However, if that's not enough, you could simply refer to your request and ask for the base URL as follows

request()->getSchemeAndHttpHost();

This will output the base URL of the site. You could then append your own routes to it. 

h15c-laravel-base-url.jpg

More about the url() helper can be found in the Laravel documentation. The function allows you to generate fully qualified URL to the given path. This means if you wish to refer to /edit/profile/ you could simply write: 

url('edit/profile/'); // Outputs https://site.dev/edit/profile/

You could also make use of url()->current(), url()->full() and url()->previous(); as your application needs. 

If you have any questions, ask them below. Do not forget to share this small tutorial on social media.

Share this content on your social channels -

Replies, Feedback and Questions

Radhika Deshpande
Radhika Deshpande
Computer Science

06 Jan, 2019

Very well explained!

Mohit Patil
Mohit Patil
Software Developer and an Aspiring Entrepreneur

11 Jan, 2019

Can you tell me when to include the slash in the url path? Also among all the methods of base URL which one do you recommend using? Does it have any performance benefits? 

Kaustubh Katdare
Kaustubh Katdare
CEO @ CrazyEngineers, TEDx Speaker, Guitarist

11 Jan, 2019

The paths are relative. Do not include a / at the start of the path that you are including. I personally use the url() helper for all the URLs. It's easy and convenient and easy to read in the code. No there aren't any performance benefits to either approach.