raunak-gupta
10/11/2016 - 8:11 AM

The cleanest way to add the active class to bootstrap link components How to Dynamically Add Active Class to a Navigation Menu Based on URL.

The cleanest way to add the active class to bootstrap link components How to Dynamically Add Active Class to a Navigation Menu Based on URL. This code can be written in app/Helpers/Helpers.php.

<?php
if (!function_exists('isActiveRoute')) {
    /*
      |--------------------------------------------------------------------------
      | Detect Active Route
      |--------------------------------------------------------------------------
      |
      | Compare given route with current route and return output if they match.
      | Very useful for navigation, marking if the link is active.
      | class="{{ isActiveRoute('dashboard') }}"
     */

    function isActiveRoute($route, $output = "active") {
        $current_url = Request::url();
        $current_url = parse_url($current_url, PHP_URL_PATH);
        $current_url = trim($current_url, '/');

        if (strpos($current_url, $route) !== false)
            return $output;
    }
}

if (!function_exists('areActiveRoutes')) {
    /*
      |--------------------------------------------------------------------------
      | Detect Active Routes
      |--------------------------------------------------------------------------
      |
      | Compare given routes with current route and return output if they match.
      | Very useful for navigation, marking if the link is active.
      | class="{{ areActiveRoutes(['client.index', 'client.create', 'client.show']) }}"
      | ->  https://laracasts.com/discuss/channels/general-discussion/whats-the-cleanest-way-to-add-the-active-class-to-bootstrap-link-components
     */

    function areActiveRoutes(Array $routes, $output = "active") {
        $current_url = Request::url();
        $current_url = parse_url($current_url, PHP_URL_PATH);
        $current_url = trim($current_url, '/');

        foreach ($routes as $route) {
            if (strpos($current_url, $route) !== false)
                return $output;
        }
    }
}
?>

<!-- Usage -->
<li class="{{ isActiveRoute('home') }}"><a href="{{ route('home') }}">Home</a></li>

<!-- or -->
<li class="{{ areActiveRoutes(['client.index', 'client.create', 'client.show']) }}"><a href="{{ route('client.index') }}"><i class="fa fa-users"></i> Clients</a></li>