When displaying menu items in the navigation bar, it's important to highlight the current active page visually. Let's see a few ways to do this in Laravel.
Single Route - By Name
If you use route names in your application (and you should!), you can use the request()->routeIs([name])
helper.
request()->routeIs('dashboard')
This helper will return true/false depending on whether the current route matches the pattern. For example:
// true if the current route is the dashboardrequest()->routeIs('dashboard') // true if the current route is dashboard or dashboard/listrequest()->routeIs('dashboard.*') // true if the current route is dashboard/list but not dashboard/create or dashboardrequest()->routeIs('dashboard.list') // true if the current route is in the expenses group (expenses, expenses/create, expenses/1/edit)request()->routeIs('expenses.*')
Multiple Routes - By Name
Besides the simple single route name check, you can also have a more complex check with multiple patterns:
// true if the current route is in the expenses group or bank-accounts grouprequest()->routeIs(['expenses.*', 'bank-accounts.*'])
This is useful if you want to highlight multiple menu items as active.
Checking for URL - Without Route Name
If you don't use route names, you can check for a specific URL instead.
In this case, we have Settings as our dropdown that we need to highlight as soon as we are in any of the settings pages:
<ul id="dropdown-pages" class="{{ request()->is('settings/*') ? '' : 'hidden' }} py-2 space-y-2">
As you can see, we have used the request()->is('settings/*')
helper to check if we are in any of the settings pages. This allows us to check for URL patterns, not just route names or groups.
Do you know any other ways to check for an active menu item? Let us know in the comments below!
Excellent