I\'m trying to set active class in my list item, but it doesn\'t work.
My code in blade:
@foreach($data as $site)
Make a function in helper.
function activeMenu($uri = '') {
$active = '';
if (Request::is(Request::segment(1) . '/' . $uri . '/*') || Request::is(Request::segment(1) . '/' . $uri) || Request::is($uri)) {
$active = 'active';
}
return $active;
}
Use it in sidebar.
<li class="{{ activeMenu('dashboard') }}"></li>
<li class="{{ activeMenu('student') }}"></li>
<li class="{{ activeMenu('teacher') }}"></li>
Use short if. Example:
<a href="#" class="{{ (\Request::route()->getName() == 'this.route') ? 'active' : '' }}">
I am currently using Laravel 5.6.* and my solution is:
<a href="#" class="nav-link {{ request()->is('users*') ? 'active' : '' }}">Users</a>
I am using Laravel 7 and Bootstrap Dropdown. So there are several collapse items that depend on the link, this works:
<li class="nav-item {{ Route::is('users.*') || Route::is('user.*') ? 'active' : '' }}">
Use is() method. For example:
<li class="{{ request()->is('sites/*/edit') ? 'active' : '' }}"
Laravel 7+
For named routes with prefixes like admin
or admin.view
or admin.edit
etc...
<li class="{{ Str::startsWith(Route::currentRouteName(), 'admin')) ? 'active' : '' }}">...</li>
A bit verbose but you can look into making a custom function like is_active('admin')