Skip to content Skip to sidebar Skip to footer

How Can I Add Active Class In Laravel On Header Items When They're Clicked?

I've been trying to get active class on my header items when they are clicked. I have a menu and my li items inside of a menu leads to specific pages on my website. Now I want to a

Solution 1:

Try the below, this is from the linked thread and https://laravel.com/docs/5.4/requests#request-path-and-method:

<divclass="container"><divclass="row"><divclass="col-md-10 col-sm-12 col-xs-12"style="width: 43.333333% !important;position: relative;right: 1.35rem;margin-bottom: 12px;"><!-- Nav start --><divclass="navbar navbar-default"role="navigation"><divclass="navbar-collapse collapse"id="nav-main"><ulclass="nav navbar-nav"><liclass="{{ request()->is('/') ? 'active' : '' }}"><aid="newmenu"style="background-color: rgba(255,255,255,0.1);"href="{{url('/')}}">{{__('Beauty treatments')}}</a></li>
            @foreach($show_in_top_menu as $top_menu) @php $cmsContent = App\CmsContent::getContentBySlug($top_menu->page_slug); @endphp
            <liclass="{{ request()->is('cms/*') ? 'active' : '' }}"><aid="newmenu"href="/demo/public/jobs?country_id%5B%5D=231">{{__('Hair')}}</a></li>
            @endforeach

            <liclass="{{ request()->is('/') ? 'active' : '' }}"><aid="newmenu"href="{{url('/')}}">{{__('Hands')}}</a></li><liclass="{{ request()->is('/') ? 'active' : '' }}"><aid="newmenu"href="{{url('/')}}">{{__('Spa Services')}}</a></li></ul><!-- Nav collapes end --></div><divclass="clearfix"></div></div><!-- Nav end --></div></div><!-- row end --></div>

Solution 2:

I usually go the way of setting a variable like the comment above and handle this through the middleware in Laravel - https://laravel.com/docs/5.7/middleware.

I create a middleware using artisan and ensure the routes go through it.

php artisan make:middleware ActiveNav

// routes/web.php
Route::group(['middleware' => 'active.nav'], function () {
    Route::get('/', 'HomeController@index');
    Route::get('/contact', 'ContactController@index');
    Route::get('/blog', 'BlogController@index');
});

Register the middleware in kernel.php (notice the last line in the array)

// app/Http/Kernel.php
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,'can' => \Illuminate\Auth\Middleware\Authorize::class,'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,'active.nav' => \App\Http\Middleware\SetActiveNav::class,
];

I then check the route in the middleware and set a variable which I share with the Views

// app/Http/Middleware/ActiveNav.phppublicfunctionhandle($request, Closure$next)
{
    $active['home']     = '';
    $active['contact']  = '';
    $active['blog']     = '';

    $route = $request->getPathInfo();

    switch(true) {
        case(strstr($route, '/blog')) :
            $active['blog'] = 'active';
            break;
        case(strstr($route, '/contact')) :
            $active['contact'] = 'active';
            break;
        default:
            $active['home'] = 'active';
    }

    \View::share('active', $active );

    return$next($request);
}

}

Then I check in the nav:

// nav.blade.php
<li class="nav-item ">
    <aclass="nav-link {{$active['home']}} btn"href="/">Home</a>
</li>
<liclass="nav-item"><aclass="nav-link {{$active['blog']}}"href="/blog">Blog</a></li><liclass="nav-item"><aclass="nav-link {{$active['contact']}}"href="/contact">Contact</a></li>

You can use middleware whenever you need to run a certain function on a route (or a group of routes). Also no JS required this way :)

Solution 3:

You can simply create a custom helper method inside a helper file:

if(!function_exists('is_active_menu')){

    functionis_active_menu($url){

        return \Route::is($url) ? 'active' : '';
    }

}

and then use :

<liclass="list-item {{ is_active_menu('home') }} ">Men</li>

You can use wildcards like home* in is() function.

Solution 4:

You can use is method of request function The is method allows you to verify that the incoming request path matches a given pattern. For example:

  • If your url is www.yourdomain.com
<liclass="{{request()->is('/') ? 'active' : ''}}"></li>
  • If yur url is www.yourdoamin.com/page1
<liclass="{{request()->is('page1') ? 'active' : ''}}"></li>
  • If yur url is www.yourdoamin.com/page1/category1
<liclass="{{request()->is('page1/category1') ? 'active' : ''}}"></li>
  • You may use the * character as a wildcard.

    www.yourdomain.com/page1/category1

<liclass="{{request()->is('page1/*') ? 'active' : ''}}"></li>
  • www.yourdomain.com/page1/category1/subcategory1
<liclass="{{request()->is('page1/*') ? 'active' : ''}}"></li>

Docs https://laravel.com/docs/5.8/requests

Post a Comment for "How Can I Add Active Class In Laravel On Header Items When They're Clicked?"