Skip to content

Instantly share code, notes, and snippets.

@0xShamil
Created April 2, 2017 16:45
Show Gist options
  • Save 0xShamil/c25fd1827e81d3e9413fe631df0b50d9 to your computer and use it in GitHub Desktop.
Save 0xShamil/c25fd1827e81d3e9413fe631df0b50d9 to your computer and use it in GitHub Desktop.
Add active class to bootstrap link components in Laravel 5
<?php
/**
* Load this file with composer autoload
*/
if (! function_exists('active')) {
function active($route, $class = 'active')
{
/**
* Route checking can be done here,
* but doing it in a seperate class file is a bit cleaner and maintainable
*/
return RouteActiveStateChecker::active($route, $class);
}
}
<?php
use Route;
/**
* Create this file in app/ directory.
* Set namespace.
* Import it in helpers.php to use the static methods
*/
class RouteActiveStateChecker
{
/**
* Determine if the provided route is active.
*
* @param string $route
* @return bool
*/
static function isActiveRoute($route)
{
if (Route::currentRouteName() == $route) {
return true;
}
return false;
}
/**
* Get the active class if the active path is provided.
*
* @param string $route
* @param string $class
* @return string|null
*/
static function active($route, $class='active')
{
return self::isActiveRoute($route) ? $class : null;
}
}
<ul class="nav">
<li class="{{ active('dashboard.index') }}">
...
</li>
<li class="{{ active('posts.index') }}">
....
</li>
<li class="{{ active('categories.index') }}">
...
</li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment