Getting current URI in Laravel 5.7
Asked Answered
O

3

7

I am aware that in the previous versions of Laravel (e.g. 4), one could get the current uri through

Route::current()->uri();

However, this doesn't seem to work in Laravel 5.7 or later. I am wondering how it should be rewritten. Please note that I am accessing the uri in a blade view and hence cannot use non-static methods.

Oldster answered 6/3, 2019 at 6:14 Comment(1)
URI is a more generic term that covers URLs (including other things). In the context of a webpage there's no difference between URI and URLBraden
A
20

You can get current url in laravel using folling methods.

// Get the current URL without the query string...
echo url()->current();

// Get the current URL including the query string...
echo url()->full();

// Get the full URL for the previous request...
echo url()->previous();

Each of these methods may also be accessed via the URL facade:

use Illuminate\Support\Facades\URL;

echo URL::current();

For more information you can read full documentation here.

Abramabramo answered 6/3, 2019 at 6:25 Comment(0)
S
6

That should still work - but it may not work as expected if the current path is not named. You should probably instead get the path from the request.

Request::path();

It's probably also checking the API of the request instance as there are a number of related methods you can call on it.

Request::root();
Request::url();
Request::fullUrl();
Request::fullUrlWithQuery();
Smalltime answered 6/3, 2019 at 6:17 Comment(0)
T
1
public function yourMethod(Request $request)
{
    return view('your-view', [ 'current-uri' => $request->route()->uri() ]);
}

Documentation

Tam answered 6/3, 2019 at 6:23 Comment(1)
Yes, but I cannot call url()->current()->uri().Oldster

© 2022 - 2024 — McMap. All rights reserved.