Search code examples
phplaravellaravel-5bootstrap-4navigation

Setting active class for menu items dynamically in laravel


I'm creating a laravel application using bootstrap 4.

I have my main navigation menu in app.blade.php . And I have four main blades, About,Product,Contact and Blog.

Then I needed to change the menu item active class according to the current page. As the menu being loaded dynamically from the app.blade.php I had to set the active class for current page in the navigation menu dynamically.

What I did was in every blade I've defined a variable called, $currentpage and assign page name in to it, assume it's blog.blade.php

<?php $currentPage = 'blog';?>
@extends('layouts.app')

@section('content')

and in the app.blade.php,

<li class="<?php if($currentPage =='blog'){echo 'nav-item active';}?>">
                            <a class="nav-link " href="{{ url('/blog') }}">{{ __('sentence.Blog') }}</a>
                        </li>

So this works properly..

but I want to know Is this the correct way of doing it and what are the other possible ways to fulfill my requirement


Solution

  • Instead of defining a $currentPage variable in the layout files, you could use the
    request()->is() method:

    <li class="nav-item {{ request()->is('blog') ? 'active' : ''}}">
        <a class="nav-link " href="{{ url('blog') }}">{{ __('sentence.Blog') }}</a>
    </li>
    

    The is() method essentially takes the current url path for the request and uses Str::is() to check against the pattern you've passed in.

    This way you only having to check if the current URL matches the link URL and you don't have to define an extra piece of data somewhere else in your application.