Apply active class to menu items based on which page is currently being viewed

Submitted by Novica89 - 8 years ago

Learn how to make a function to easily test which menu items should be marked as active depending on which page you are currently viewing in your browser. Add class of active to bootstrap menu items on different pages. Wherever you need to apply an active class ( or any other class ) in order to make a menu item active depending on which page you are currently viewing, or for any other sort of functionality you might need, this is the way you can do it with Laravel ( or plain PHP just a bit differently ) Watch the video on how to do it https://www.youtube.com/watch?v=E1oit3sd-7k

Create a custom function

function current_page($uri = "/") {
    return strstr(request()->path(), $uri);
}

Then, on a list item on your menu for example, do this kind of a check, in order to add a class
 to it depending if the user is currently on that particular passed in page.
 
<li {{ (current_page("contact")) ? 'class=active' : '' }}><a href="{{ url('/contact') }}"> Contact</a></li>