We are developing the next version of CrazyEngineers. If you wish to receive latest updates and early access, click the link below.
How to get Base URL in Laravel - Tutorial
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:
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 -
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
This will output the base URL of the site. You could then append your own routes to it.
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.#PHP #Laravel
Replies, Feedback and Questions
Very well explained!
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?
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.
Is there a way to get the base URL in Laravel using jQuery? Will this work?
Rashmi - jQuery acts on the front-end; hence it has got nothing to do with how you get the base url in Laravel. Here's something you could try with jQuery:
let getUrl = window.location;
let baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/');
In the first line, we set window.location to variable getUrl. The getUrl has all the information you need.
In the second step, we assign the protocol "http" or "https", followed by the host aka sitename and followed by the path-name.
Give it a try and let me know if it solves your problem.