How to active menu in laravel
<li class="active">
<a href="{{ route('admin.home') }}">
<i class="fa fa-bank"></i> <span>Home</span>
</a>
</li>
<li class="{{ ($some_condition_if_active) ? 'active' : '' }}">
Solution 1. Exact URL
Probably, the most simple one – you just check the exact URL and see if it matches:
<li class="{{ (request()->is('admin/home')) ? 'active' : '' }}">
Solution 2. Starting with the URL
This one is similar, but more flexible – will also match any other URL starting with the one we want, like /admin/home/subpage or /admin/home/1/edit.
We use asterisk (*) symbol for it.
<li class="{{ (request()->is('admin/home*')) ? 'active' : '' }}">
Solution 3. Matching URL Segment
Another useful helper is to get URL segments by number.
<li class="{{ (request()->segment(2) == 'home') ? 'active' : '' }}">
So, this one will match any URL like /admin/home, /user/home/edit etc.
Solution 4. Matching Route by Name
The one that I personally recommend. Route names is a really powerful weapon in case your URLs change for some reason. Let’s say we attached route names with this line in routes/web.php:
Route::middleware(['auth'])->prefix('admin')->name('admin.')->group(function() {
Route::resource('home', 'Admin\HOmeController');
});
So we should match any route name like admin.home.index or admin.home.create for menu item to be active.
And here we use Route::getCurrentName() method.
<li class="{{ (strpos(Route::currentRouteName(), 'admin.home') == 0) ? 'active' : '' }}">
In this case, all URLs assigned to our resourceful controller will be matched, like /admin/home, /admin/home/create, /admin/home/1/edit etc.
How to active menu in laravel
Reviewed by TechTubeHQ
on
August 22, 2022
Rating:

No comments: