10

Get The Current URL In Laravel Controller & View

 3 years ago
source link: https://www.codewall.co.uk/get-the-current-url-in-laravel-controller-view/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The Answer: 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



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK