Development

Current Route Checking in Laravel

Everytime I get my teeth into a new project on Laravel, I always end up searching Google for the same things. One of those times is when I come to set up navigation, and I want to dynamically apply the active class to navigation items.

Introducing currentRouteNamed(). There's an undocumented method in Illuminate/Routing/Router that will return true or false based on whether the parameter you give matched the name of the current route. Event better, it accepts wildcards.

<a 
 class="@if(Route::currentRouteNamed('customers*')) active @endif"
 href="{{ route('customers') }}">
    Customers
</a>

Notice the use of the asterisk. The wildcard (*) means even if you're currently on the route customers.create or customers-list, the method will return true. So the menu item will appear active for all sub pages. You will need to be using named routes for this particular method. To see more, or for similar methods, you can check out the code or API.