Get The Current URL In Laravel Controller & View

Accessing the current URL can be done by making use of the global url variable that is accessible in Laravel controllers. It can be called directly or can be imported as a facade that is then used as an ordinary static class. The URL facade exposes all the same methods as the global url variable offers.


See the following working examples to see how to get the current URL in both Laravel controllers and view files.


Get The Current URL Within Controllers

$currentUrl = url()->current();
// OR
$currentUrl = URL::current();

To utilize the second method, ensure you add the following use statement to the top of your controller –


use Illuminate\Support\Facades\URL;


Get The Current URL Within Views

Accessing the URL string value inside a view can be achieved just like accessing any other variables you want to access in your views. By using the view()->with() function.

This would look something like the following –


Controller Code

$currentUrl = url()->current();
// OR
$currentUrl = URL::current();
return view('products.create')->with('currentUrl', $currentUrl);

View Code

{{$currentUrl}} // Echos the current url string

Source: codewall


The Tech Platform

www.thetechplatform.com