One of the most common operations on each website is probably to allocate a “active” CSS class to the menu item that is currently open. There are several ways to detect this status, let’s go.

We assume that the code will be based on Bootstrap and that the active menu item will have this:


<li>
    <a href=" route("admin.cities.index') }}">
        <i class="fa fa-flag"></i> <span>Countries</span>
    </a>
</li>
<li class="active">
    <a href=" route("admin.cities.index') }}">
        <i class="fa fa-bank"></i> <span>Cities</span>
    </a>
</li>
<li>
    <a href=" route("admin.cities.index') }}">
        <i class="fa fa-dollar"></i> <span>Currencies</span>
    </a>
</li>

Now the part that interests us is Class = “active”. In Real Blade, it should be as follows:


<li class="{{ ($some_condition_if_active) ? 'active' : '' }}">  

So how to define that $ some_Condition_if_active?


Approach 1. Exact URL

Probably, the easiest way – you just check the exact URL and see if he corresponds:


<li class="{{ (request()->is('admin/cities')) ? 'active' : '' }}">  

We use the assistance function $ request-> is ().


Approach 2. Starting with the URL

This is similar, but more flexible – will also correspond to any other URL starting with the one we want, as / admin / cities / create Or / admin / cities / 1 / modify.

We use the asterisk


<li class="{{ (request()->is('admin/cities*')) ? 'active' : '' }}">  

Symbol for that.

Approach 3. Corresponding URL segment Another useful help is to get URL segments


<li class="{{ (request()->segment(2) == 'cities') ? 'active' : '' }}">  

By number. Therefore, this one will correspond to any URL as/ Admin / cities ,, / User / cities / Modify


etc.

Approach 4. Route of correspondence by nameThe one I personally recommend . Road names are a really powerful weapon in case your URLs change for any reason. Let’s say that we have attached the names of itinerary to this line initineraries / web.php


Route::middleware(['auth'])->prefix('admin')->name('admin.')->group(function() {
    Route::resource('cities', 'Admin\CityController');
});

:: We must therefore match any name of itinerary as admin.citures.index Or admin.

so that the menu item is active.


<li class="{{ (strpos(Route::currentRouteName(), 'admin.cities') == 0) ? 'active' : '' }}">  

And here we use the Road method :: Getcurrentname (). In this case, all the URLs assigned to our resource controller will be paired, as/ Admin / cities ,,/ admin / cities / create ,, / admin / cities / 1 / modify

etc.



Technology

Another Tech Information

Similar Posts