Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alenabdula's avatar

Determine active route resource

I have following code

class Nav
{
    public static function activeItem($name)
    {
        if ( \Route::is($name) ) {
            return 'is-active';
        }
    }
}

And I use it like this to generate active menu item

<a class="nav-item {!! Nav::activeItem('about') !!}" href="{{ route('about') }}">About</a>

This works great for non-resource routes. However! If i have journal as a resource above works great on index route, but I would like it to return is-active on all resource routes.

I've modified it, but wondering if there's a cleaner way?

class Nav
{
    public static function activeItem($name)
    {
        if ( \Route::is($name) ) {
            return 'is-active';
        }
        foreach (['.index', '.create', '.edit', '.show'] as $route) {
            $rest = $name . $route;
            if ( \Route::is($rest)) {
                return 'is-active';
            }
        }
    }
}
<a class="nav-item {!! Nav::activeItem('journal') !!}" href="{{ route('journal.index') }}">Journals</a>

Thanks.

0 likes
3 replies
Baryla's avatar

Wouldn't it be easier to have this in your anchor and completely eliminate the method on your class?

<a class="nav-item {{ str_is('journal*', Request::route()->getName()) ? 'is-active' : '' }}" href="{{ route('journal.index') }}">Journals</a>
alenabdula's avatar

I'll try it and see how it goes. I think am just over thinking this. Especially with the foreach having it run on every link anchor might not be best approach.

Thanks.

Baryla's avatar

No worries, go ahead, it's worth a try. That's how I do my navigation and it seems to work really well. :)

Please or to participate in this conversation.