Laravel Blade Directive To Set Active Menu Class
<?php
Blade::directive('active', function ($expression) {
return "<?php echo active_url($expression); ?>";
});
<?php
if (! function_exists('active_url')) {
function active_url($pattern, $default = 'active')
{
$path = request()->decodedPath();
if (@preg_match('#^'.$pattern.'\z#u', $path)) {
return $default;
}
}
}
<ul class="nav nav-pills">
<li role="presentation" class="@active('foods/?.*')"><a href="#">Foods</a></li>
<li role="presentation" class="@active('glossary/?.*')"><a href="#">Glossary</a></li>
<li role="presentation" class="@active('recipes/?.*')"><a href="#">Recipes</a></li>
<li role="presentation" class="@active('tools/?.*')"><a href="{{ url('/tools') }}">Tools</a></li>
</ul>