Laravel: How to Make Menu Item Active by URL/Route when using resource controller method
Hello good day, hope you are having a "codie" day ?
In every website or web application, their is usually a need to let the current route be known by the user by adding a class 'active' to the menu item. In this tutorial, I will be assuming, you are using bootstrap framework, which provides class for setting active menu item out of the box by just adding 'active' menu link.
let assume you have the below menu
<li>
<a href="{{ route('user.index') }}">
<i class="fa fa-user"></i> <span>All Users</span>
</a>
</li>
<li class="active">
<a href="{{ route('user.create') }}">
<i class="fa fa-users"></i> <span>Create User</span>
</a>
</li>
<li>
<a href="{{ route('user.show') }}">
<i class="fa fa-gear"></i> <span>User Profile</span>
</a>
</li>
The part we need is the class set to active. In the blade template, it should be like this, using ternary condition method.
/*
*It checks if some condition is met
* if the expression in the brack returns true
* then menu item is set to active and vice versa
*/
<li class="{{ ($some_condition_if_active) ? 'active' : '' }}">
Option 1 is using the exact url
It is the simplest way of doing it, but i don't find it quite tidy enough. We just check for the exact URL and see if it matches like this
<li class="{{ (request()->is('user/create')) ? 'active' : '' }}">
We use helper function $request->is().
Option 2 is starting with the URL
This quite my favourite because i like working with resource controller. It looks similar to first option but a lot more flexible. It will match any url starting with one we want like /user , user/create, user/edit or user/show
We use asterisk (*) symbol for it.
<li class="{{ (request()->is('user/*')) ? 'active' : '' }}">