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

Stank0V01's avatar

How to make active class when it have sub category?

Hello guys im tryna to make active class when is clicked on subcategory

            <div class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    <li class="{{ isActive('/') }}"><a href="{{ url('/') }}"><b class="fa fa-home"></b> @lang('messages.home')</a></li>
                    @foreach ($categories as $cat)
                        <li class="{{ $cat->children->count() > 0 ? 'dropdown' : ''}} {{ isActive('/category/'.$cat->slug) }}">
                            <a href="{{ url('/category/'.$cat->slug) }}" class="{{ $cat->children->count() > 0 ? 'dropdown-toggle' : ''  }}"
                               data-toggle="{{ $cat->children->count() > 0 ? 'dropdown' : ''  }}">
                                {{$cat->name}} {!! $cat->children->count() > 0 ? '<b class="fa fa-caret-down"></b>' : '' !!}
                            </a>
                            <ul class="dropdown-menu">
                            @foreach($subcategories as $sub)
                                @if($sub->parent_id == $cat->id)
                                        <li><a href="{{ url('category/'.$sub->slug) }}">{{ $sub->name }}</a></li>
                                @endif
                            @endforeach
                            </ul>
                         </li>
                    @endforeach
                </ul>
            </div>

How it will be done (isActive function is my custom helper that i make here it is)

<?php
if(!function_exists("isActive")) {
    /**
     * @param $url
     * @return string
     */
    function isActive($url) {
        return $_SERVER['REQUEST_URI'] == $url ? 'active' : '';
    }
}
0 likes
0 replies

Please or to participate in this conversation.