How to get current URL in Laravel

One common task that developers encounter while working with Laravel is getting the current URL of the page. The reason can be anything like checking which menu should be active or the user has the right to access specific URLs.

In this article, we will explore different ways of getting the current URL in Laravel.

Using the Request Object

One of the easiest ways of getting the current URL in Laravel is by using the Request object. The Request object provides access to various information about the current HTTP request, including the URL. Here's an example of how to use the Request object to get the current URL:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
 
class HomeController extends Controller
{
    public function index(Request $request)
    {
        $url = $request->url();
        return view('welcome', compact('url'));
    }
}

Here, we are using the url() method of the Request object to get the current URL. This method returns the full URL including the scheme and host.

Using the URL Facade

Another way of getting the current URL in Laravel is by using the URL facade. The URL facade provides a set of methods that allow you to generate URLs for different routes and actions. However, it also provides a method to get the current URL. Here's an example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
 
class HomeController extends Controller
{
    public function index(Request $request)
    {
        $url = URL::current();
        $fullUrl = URL::full();
        return view('welcome', compact('url', 'fullUrl'));    
    }
}

In this example, we are using the `current()` method of the URL facade to get the current URL.

Using the URL Helper

The url() helper can be used to get the current URL. With using this method, we don't need to import or implement any classes and it can be used directly to blade files without any dependencies.

<?php
namespace App\Http\Controllers;

class HomeController extends Controller
{
    public function index()
    {
        $url = url()->current();
        $fullUrl = url()->full();
        return view('welcome', compact('url', 'fullUrl'));    
    }
}

Just like the URL facade we directly call current() or full() methods on url helper and it will automatically manage dependencies for it.

Conclusion

Getting the current URL in Laravel is a simple task that can be accomplished using various methods. In this post, we have taken examples of three different ways of getting the current URL: using the Request object, using the URL facade, and using url helper.

You can use any of these methods as per your requirements and coding style. But we need to check the request object while using it in the view file or in other words we need to resolve dependencies.