Laravel: How to Get Current Route Name? (v5 ... v7)
Asked Answered
P

35

314

In Laravel v4 I was able to get the current route name using...

Route::currentRouteName()

How can I do it in Laravel v5 and Laravel v6?

Plummer answered 5/5, 2015 at 7:27 Comment(5)
which namespace should i use to find route name? i have used Illuminate\Support\Facades\Route but result is null.Plummer
That is the correct class. Your route has probably no name assigned. Note that the route name and the URI is not the same.Frumpy
Here is right answer #27397987Ducky
Why would you need it?Karlynkarma
@YevgeniyAfanasyev In a collaborative project with multiple people, sometimes you could lose track of which code leads to which one. By using this function, you can navigate your way better. But, in production, I am not really sure of the usefulness of this.Drabbet
K
599

Try this

Route::getCurrentRoute()->getPath();

or

\Request::route()->getName()

from v5.1

use Illuminate\Support\Facades\Route;
$currentPath= Route::getFacadeRoot()->current()->uri();

Laravel v5.2

Route::currentRouteName(); //use Illuminate\Support\Facades\Route;

Or if you need the action name

Route::getCurrentRoute()->getActionName();

Laravel 5.2 route documentation

Retrieving The Request URI

The path method returns the request's URI. So, if the incoming request is targeted at http://example.com/foo/bar, the path method will return foo/bar:

$uri = $request->path();

The is method allows you to verify that the incoming request URI matches a given pattern. You may use the * character as a wildcard when utilizing this method:

if ($request->is('admin/*')) {
    //
}

To get the full URL, not just the path info, you may use the url method on the request instance:

$url = $request->url();

Laravel v5.3 ... v5.8

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

Laravel 5.3 route documentation

Laravel v6.x...7.x

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

** Current as of Nov 11th 2019 - version 6.5 **

Laravel 6.x route documentation

There is an option to use request to get route

$request->route()->getName();
Kutaisi answered 5/5, 2015 at 11:57 Comment(9)
Do you have an idea how to filter this for instance if one only wants to print in the view api routes api/...Hinze
Route::currentRouteName(); perfect :)Ubangi
$request::route()->getName() if you're already using the $request, or you can use the global helper request()::route()->getName().Perkins
@Daniel Dewhurst: Maybe it works on v < 5.7, but with v5.7 you must not use it statically, instead request()->route()->getName() is the way to go.Nanji
Using the request() helper function is particularly useful in views. request()->route()->getName() is the best option.Alegar
request()->routeIs('route.name') latest wayPriedieu
There is also the Route::is('admin.*') that checks if the route name matches the given patterns.Ambagious
agree with @DanielDewhurst you can check all the method in here Illuminate/Routing/RouteAlgarroba
I have used all 3 solutions in Laravel 8 version and none of them are working. // echo $route = Route::current(); echo $name = Route::currentRouteName(); echo $action = Route::currentRouteAction();Polliwog
T
43

Using Laravel 5.1, you can use

\Request::route()->getName()
Trigonometry answered 8/10, 2015 at 7:40 Comment(1)
this also works when you put it on the view as {{ route(\Request::route()->getName()) }} . Thanks so much!Surfing
P
29

Found a way to find the current route name works for laravel v5 , v5.1.28 and v5.2.10

Namespace

use Illuminate\Support\Facades\Route;

and

$currentPath= Route::getFacadeRoot()->current()->uri();

For Laravel laravel v5.3 you can just use:

use Illuminate\Support\Facades\Route;

Route::currentRouteName();
Plummer answered 5/5, 2015 at 7:40 Comment(2)
@Jonathan I believe it's always better to use the full namespace in order to avoid any potential conflict.Flitting
any sugestion for laravel 8?Polliwog
S
27

If you want to select menu on multiple routes you may do like this:

<li class="{{ (Request::is('products/*') || Request::is('products') || Request::is('product/*') ? 'active' : '') }}"><a href="{{url('products')}}"><i class="fa fa-code-fork"></i>&nbsp; Products</a></li>

Or if you want to select just single menu you may simply do like this:

<li class="{{ (Request::is('/users') ? 'active' : '') }}"><a href="{{url('/')}}"><i class="fa fa-envelope"></i>&nbsp; Users</a></li>

Also tested in Laravel 5.2

Hope this help someone.

Saber answered 11/5, 2016 at 8:35 Comment(4)
also tested in Laravel 5.3Bushweller
also tested in Laravel 7.5.2Dundee
tested in Laravel 5.7Elba
This is the easiest way and it still works under Laravel 9.1 ThanksHideous
S
25

If you need url, not route name, you do not need to use/require any other classes:

url()->current();
Soldier answered 17/3, 2016 at 14:4 Comment(3)
This returns an error: "Call to a member function current() on a non-object". url() returns a string, not an object, so i dont think this could ever have worked. Perhaps you were thinking about some other method or object, instead of url()?Ettore
Nah, I use this on daily basis. Check official docsSoldier
I see. This only works in version 5.2 or greater. But its quite nice.Ettore
R
23

In laravel 7 or 8 use helper function

Get Current Route Name
request()->route()->getName()

To check if route is current better to create your own method for request class using macro

In AppServiceProvider In boot method :

use Illuminate\Support\Facades\Request;
public function boot()
    {
        Request::macro('isCurrentRoute', function ($routeNames) {
            $bool = false;
            foreach (is_array($routeNames) ? $routeNames : explode(",",$routeNames) as $name) {
               if(request()->routeIs($name)) {
                   $bool = true;
                   break;
                }
             }

             return $bool;
        });
    }

You can used this method in blade or controller

request()->isCurrentRoute('foo') // string route
request()->isCurrentRoute(['bar','foo','xyz.*']) //array routes
request()->isCurrentRoute('blogs,foo,bar,xyz.*') //string route seperated by comma

You can use inbuilt laravel route method

request()->routeIs('home');
request()->routeIs('blogs.*'); //using wildcard
Rosenberger answered 18/9, 2021 at 6:51 Comment(1)
It should be request()->routeIs('home') in this instance to check route name or request()->is('home'). The latter Determines if the current request URI matches a pattern, while the former Determines if the route name matches a given pattern. So the former routeIs method I would suggest. Definitely not route()->is('home'). You will receive no such method error or route() method expecting 1 argument 0 given. [Source][ laravel.com/api/8.x/Illuminate/Http/Request.html ]Cartoon
G
15

Laravel 5.2 You can use

$request->route()->getName()

It will give you current route name.

Gosh answered 15/4, 2016 at 7:55 Comment(1)
This is actually incorrect. the name() method will add or change the name, while the getName() method returns it.Groningen
P
15

In 5.2, you can use the request directly with:

$request->route()->getName();

or via the helper method:

request()->route()->getName();

Output example:

"home.index"
Plenitude answered 4/7, 2016 at 15:50 Comment(0)
C
9

Accessing The Current Route

Get current route name in Blade templates

{{ Route::currentRouteName() }}

for more info https://laravel.com/docs/5.5/routing#accessing-the-current-route

Choochoo answered 13/9, 2018 at 12:29 Comment(0)
H
6

Shortest way is Route facade \Route::current()->getName()

This also works in laravel 5.4.*

Hollar answered 18/7, 2016 at 8:54 Comment(0)
D
5

In a controller action, you could just do:

public function someAction(Request $request)
{
    $routeName = $request->route()->getName();
}

$request here is resolved by Laravel's service container.

getName() returns the route name for named routes only, null otherwise (but you could still explore the \Illuminate\Routing\Route object for something else of interest).

In other words, you should have your route defined like this to have "nameOfMyRoute" returned:

Route::get('my/some-action', [
    'as' => 'nameOfMyRoute',
    'uses' => 'MyController@someAction'
]);
Disenable answered 30/8, 2015 at 23:28 Comment(0)
D
5

You can use in template:

<?php $path = Route::getCurrentRoute()->getPath(); ?>
<?php if (starts_with($path, 'admin/')) echo "active"; ?>
Displayed answered 28/10, 2015 at 7:15 Comment(0)
L
5

In my opinion the most easiest solution is using this helper:

request()->route()->getName()

For the docs, see this link

Liquidambar answered 28/8, 2019 at 20:27 Comment(1)
I think it is better choice in blade.Triangulation
T
5

You can use bellow code to get route name in blade file

request()->route()->uri
Told answered 4/5, 2020 at 10:12 Comment(0)
H
4

Request::path(); is better, and remember to use Request;

Hazing answered 24/2, 2016 at 6:44 Comment(0)
S
4

Now in Laravel 5.3 I am seeing that can be made similarly you tried:

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

https://laravel.com/docs/5.3/routing#accessing-the-current-route

Satyr answered 3/10, 2016 at 2:40 Comment(0)
B
4

Accessing The Current Route(v5.3 onwards)

You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request:

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

Refer to the API documentation for both the underlying class of the Route facade and Route instance to review all accessible methods.

Reference : https://laravel.com/docs/5.2/routing#accessing-the-current-route

Balalaika answered 25/8, 2018 at 12:55 Comment(0)
S
3
$request->route()->getName();
Scanty answered 6/6, 2019 at 5:40 Comment(0)
M
3

first thing you may do is import namespace on the top of class.

use Illuminate\Support\Facades\Route;

laravel v8

$route = Route::current(); // Illuminate\Routing\Route
$name = Route::currentRouteName(); // RouteName
$action = Route::currentRouteAction(); // Action

Laravel v7,6 and 5.8

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();
Membranous answered 17/4, 2021 at 23:51 Comment(0)
F
3

use laravel helper and magic methods

request()->route()->getName()
Feodore answered 8/9, 2021 at 12:56 Comment(0)
L
2

Looking at \Illuminate\Routing\Router.php you can use the method currentRouteNamed() by injecting a Router in your controller method. For example:

use Illuminate\Routing\Router;
public function index(Request $request, Router $router) {
   return view($router->currentRouteNamed('foo') ? 'view1' : 'view2');
}

or using the Route facade:

public function index(Request $request) {
   return view(\Route::currentRouteNamed('foo') ? 'view1' : 'view2');
}

You could also use the method is() to check if the route is named any of the given parameters, but beware this method uses preg_match() and I've experienced it to cause strange behaviour with dotted route names (like 'foo.bar.done'). There is also the matter of performance around preg_match() which is a big subject in the PHP community.

public function index(Request $request) {
    return view(\Route::is('foo', 'bar') ? 'view1' : 'view2');
}
Lorrielorrimer answered 24/10, 2017 at 8:8 Comment(0)
E
2

It doesn't need to memorize anything, when you would like some variable of Request, by dd(request()) can assess which variable is prominent for you. In the below image, it is clear. enter image description here

So, if you would like to get the path, obviously, this code will show

dd(request()->getpathInfo())

don't forget to embed use Illuminate\Http\Request; For instance:

if(request()->getpathInfo()=="/logadmin"){
do somethings....
}
Eck answered 25/12, 2022 at 7:25 Comment(0)
M
1

In a Helper file,

Your can use Route::current()->uri() to get current URL.

Hence, If you compare your route name to set active class on menu then it would be good if you use

Route::currentRouteName() to get the name of route and compare

Mongrel answered 25/5, 2017 at 4:45 Comment(0)
R
1

I have used for getting route name in larvel 5.3

Request::path()

Racehorse answered 12/7, 2017 at 11:21 Comment(0)
B
1

Solution :

$routeArray = app('request')->route()->getAction();
$controllerAction = class_basename($routeArray['controller']);
list($controller, $route) = explode('@', $controllerAction);
echo $route;
Broeker answered 25/1, 2019 at 14:38 Comment(0)
M
1

You can use below method :

Route::getCurrentRoute()->getPath();

In Laravel version > 6.0, You can use below methods:

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();
Multipara answered 28/11, 2019 at 10:22 Comment(1)
Gettings error: Call to undefined method Laravel\Lumen\Routing\Router::current()Polliwog
S
1

Accesing the Current Route Name in Controller

ie - http://localhost/your_project_name/edit

$request->segment(1);  // edit

( or )

$request->url();  // http://localhost/your_project_name/edit
Sabrina answered 19/3, 2020 at 11:3 Comment(0)
L
1
\Request::path()

I use this to get current uri

Livestock answered 12/8, 2021 at 14:24 Comment(0)
I
1

Here is what i use, i don't know why no one mentioned it, because it worked perfectly fine for me.

Route::getCurrentRoute()->uri ; // this returns a string like '/home'


So i use it in my master.blade.php file :

...

@if ( Route::getCurrentRoute()->uri =='/dashbord' )
   @include('navbar')
@endif
...

witch really helped me re use the same views without duplicating code.
Intertwist answered 1/2, 2022 at 1:6 Comment(0)
K
1

use helper:

app('request')->route()->getName()
Karmakarmadharaya answered 8/9, 2022 at 3:15 Comment(0)
C
1

You can use

url()->current();

it will result http://localhost:8000/your-path/...

Converted answered 22/2 at 5:26 Comment(0)
E
0

for some reasons, I couldn't use any of these solutions. so I just declared my route in web.php as $router->get('/api/v1/users', ['as' => 'index', 'uses' => 'UserController@index']) and in my controller I got the name of the route using $routeName = $request->route()[1]['as']; which $request is \Illuminate\Http\Request $request typehinted parameter in index method of UserController

using Lumen 5.6. Hope it would help someone.

Ewens answered 18/9, 2018 at 8:37 Comment(0)
A
0

You can used this line of code : url()->current()

In blade file : {{url()->current()}}

Artema answered 7/11, 2020 at 0:2 Comment(0)
A
0

There are lots of ways to do that. You can type:

\Illuminate\Support\Facades\Request::route()->getName()

To get route name.

Aerostatics answered 25/2, 2021 at 9:9 Comment(0)
B
0

no one have answer if route name or url id needed on view direct for the route name on view direct

$routeName = Request::route()->getName();

for the id from url on view

$url_id = Request::segment(2);
Bedwell answered 16/3, 2021 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.