" />
      " />
        "/>
        DEVHIDE
        • Home (current)
        • About
        • Contact
        • Cookie
        • Home (current)
        • About
        • Contact
        • Cookie
        • Disclaimer
        • Privacy
        • TOS
        Login Or Sign up

        Laravel 5.3: How-to mark navigation menu as active, when the request matches the URL (with language)

        6.2k Views Asked by checker284 At 19 December 2016 at 21:23 2025-12-17T23:41:03.170257

        I want to mark a navigation menu as "active", when the URL matches the request.

        This is working fine:

            <div class="sidebar">
                    <ul class="sidebar-menu">
                            <li {{{ (Request::is('en/dashboard') ? 'class=active' : '') }}}>
                                    <a href="/{{ App::getLocale() }}/dashboard">
                                            <i class="fa fa-dashboard"></i> <span>{{ trans('sidebar.dashboard') }}</span>
                                    </a>
                            </li>
        
                            <li {{{ (Request::is('en/settings') ? 'class=active' : '') }}}>
                                    <a href="/{{ App::getLocale() }}/settings">
                                            <i class="fa fa-gears"></i> <span>{{ trans('sidebar.settings') }}</span>
                                    </a>
                            </li>
                    </ul>
            </div>
        

        Unfortunately, it's only working and marking the navigation menu, when the URL uses the language code "en". But how can I replace the static string "en" with something more dynamic?

        I've already tried to solve this problem by using this code, but it doesn't work:

            <li {{{ (Request::is('{{ App::getLocale() }}/dashboard') ? 'class=active' : '') }}}>
        

        What's the best way to solve this?

        laravel-5 locale multilingual
        Original Q&A
        4

        There are 4 best solutions below

        1
        checker284 checker284 On 14 October 2017 at 11:28 BEST ANSWER

        I'm now using this solution, which works very well and keeps the blade clean.

        First of all, give each of your routes a unique name in your routes/web.php:

            <?php
        
            /*
            |--------------------------------------------------------------------------
            | Web Routes
            |--------------------------------------------------------------------------
            |
            | Here is where you can register web routes for your application. These
            | routes are loaded by the RouteServiceProvider within a group which
            | contains the "web" middleware group. Now create something great!
            |
            */
        
            Route::get('/admin/dashboard', 'DashboardController@getAll')->name('dashboard');
            Route::get('/admin/maintenances', 'MaintenanceController@get')->name('maintenances-overview');
            Route::get('/admin/users', 'UserController@getUsers')->name('users-overview');
        

        In your navigation blade (eg. resources/views/layouts/admin/navbar.blade.php), you can now simply reference to these names:

            <li class="{{ Route::currentRouteName() == 'dashboard' ? 'active' : '' }}">
                <a href="{{ route('dashboard') }}">Dashboard</a>
            </li>
        
            <li class="{{ Route::currentRouteName() == 'maintenances-overview' ? 'active' : '' }}">
                <a href="{{ route('maintenances-overview') }}">Maintenances</a>
            </li>
        
            <li class="{{ Route::currentRouteName() == 'users-overview' ? 'active' : '' }}">
                <a href="{{ route('users-overview') }}">Users</a>
            </li>
        

        This solution is also very helpful, when you've a multi-language site, because you don't have to use regular expressions to determine, if it's now a matching URL or not. You also can edit and update your route URLs to whatever you want to without the need to update all your blades, just because the URL got changed. The route() function returns autom. the updated URL and the Route::currentRouteName() function does always return the set name of your route. :)

        Just as hint for multi-language sites: You can simply replace the static text Users with a language variable:

            <li class="{{ Route::currentRouteName() == 'users-overview' ? 'active' : '' }}">
                <a href="{{ route('users-overview') }}">@lang('layouts/admin/navbar.users')</a>
            </li>
        

        For further information regarding localization, please take a look at the laravel.com localization documentation

        3
        Tim Lewis Tim Lewis On 19 December 2016 at 21:32

        Usually, I have a layout with these nav items extended by the current view, so something like:

        <li><a href="{{ url("home") }}>Home</a></li>
        <li><a href="{{ url("about") }}>About</a></li>
        <li><a href="{{ url("contact") }}>Contact</a></li>
        

        Then my routes:

        Route::get("/home", "BasicController@getHome");
        

        Then in my controller:

        public function getHome(){
            return view("home")->with(["page" => "home"]);
        }
        

        Now that my view home.blade.php has a $page being passed to it, and since it extends the .blade file with the nav section (usually @extends("layouts.master") or something) you can access and check the $page variable against these nav items:

        <li class="{{ $page == "home" ? "active" : "" }}><a href="{{ url("/home") }}>Home</a></li>
        

        This way you don't have to worry about matching routes in multiple languages to their active page. The only downside is that you need to include a ->with(["page" => "whatever"]) in each of your controllers that returns a view that extends that nav layout. There may be an easier way to accomplish that, but this should give you a start.

        0
        RileyManda RileyManda On 06 September 2017 at 06:49

        It simple.Just do the following in your file that contains your header or navbar and the links:

        <li class="{{ (Request::path()=='nameofyourfile' ? 'active' : '') }}">
         <a href="{{ route('nameofyourfile') }}">
                                <span class="icon fa fa-building-o" aria-hidden="true"></span><span class="title">nameofyourfile</span>
                                                        </a></li>
        
        4
        Michael Michael On 27 April 2018 at 14:28

        Just drop this little function code in your helpers class

        function is_current_route($route){
            return Route::currentRouteName() == $route ? 'class=active' : '';
        }
        

        And use it like this in your views

        <li {{is_current_route('your-route-name-here')}}>
        <a href="{{ url("/home") }}>Home</a>
        </li>
        

        Related Questions in LARAVEL-5

        • Laravel eloquent select not accepting if function
        • Laravel When Condition on a column
        • Laravel 5 Querying "Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Call to a member function addEagerConstraints() on null"
        • Cannot log-in to ReadyKit after changing a migration
        • How to fix the error [The file was not uploaded due to an unknown error.]
        • update vue2 to vue3 on Laravel 5.5 (node 12)
        • How to Create an Animated CSS Background Image Dynamically Fetched from a Database Using Laravel
        • How Can I Display Single Image From Array Of Images
        • Deprecated ReflectionParameter::getClass() Errors After Switching Back to Laravel 5.5 from Laravel 6
        • How to allow a single script in Laravel app, blade page when CSP (Content Security Policy) is enabled?
        • LARAVEL 5.7 JSONResource toArray ERROR: Declaration should be compatible
        • php - session seems as like it was never removed, even after using session remove + forget+put null
        • Laravel 5.2 + MySQL 8.0 On RDS - Connection Errors Out With "SQLSTATE[HY000] [2002]"
        • laravel Auth::logoutOtherDevices() doesn't redirect to login page?
        • i need to update url for larval website where i do try htaccess but not working

        Related Questions in LOCALE

        • Set Netbeans Console to English
        • How can I copy a date from excel to powerpoint through vba and forcing english format regardless of local formatting?
        • Formatting very large numbers to local settings in javascript
        • Accessing locale in nextJS 14 App Directory
        • GetDateFormatEx returns a non-zero value but the buffer returned by it is faulty
        • Remove grouping from numpunct of std::locale
        • Fullcalendar locale doesn't work in Chorme and Edge
        • Rewriting URL using Locale in Next JS 13
        • Javascript: Date string in different locale to Timestamp
        • How to parse country code from RFC 5646 locale string?
        • Wrong Hungarian (hu_HU) sort order
        • Change language in keycloak login page
        • After updating application locale of an android app, toast message is showing in previous language
        • How to set default stings.xml using AppCompatDelegate in android?
        • How to set language for a Vonage's sms in Laravel?

        Related Questions in MULTILINGUAL

        • Preventing redirect when changing language in DataLife engine
        • Next.js 14 Sitemap generation with multilanguage
        • Adding multi language support in C++ Builder project
        • Automatic Speech Recognition In Code Switching
        • How to set correct html property "lang" for multilingual site on Angular with Transloco?
        • Asp net BoilerPlate CreateMultiLingualMap With ProjectTo
        • How to remove Metadata from API Response (Multi Language - ASP.NET CORE)
        • Issue generating Marathi Language PDF in Flutter
        • Text Stored in Indian Languages Retrieved as ???? in Servlet Application
        • Translation of entire URLs using the app router
        • Multilingual site translation file not read or find
        • TTS : avoid spellibg instead of word pronunciation?
        • Does Doc2vec support multiple languages?And does transvec lib use for Doc2vec model?
        • multilingual duplication method html scss js gulp
        • Using asp.net localization for view models error messages

        Trending Questions

        • UIImageView Frame Doesn't Reflect Constraints
        • Is it possible to use adb commands to click on a view by finding its ID?
        • How to create a new web character symbol recognizable by html/javascript?
        • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
        • Heap Gives Page Fault
        • Connect ffmpeg to Visual Studio 2008
        • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
        • How to avoid default initialization of objects in std::vector?
        • second argument of the command line arguments in a format other than char** argv or char* argv[]
        • How to improve efficiency of algorithm which generates next lexicographic permutation?
        • Navigating to the another actvity app getting crash in android
        • How to read the particular message format in android and store in sqlite database?
        • Resetting inventory status after order is cancelled
        • Efficiently compute powers of X in SSE/AVX
        • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

        Popular # Hahtags

        javascript python java c# php android html jquery c++ css ios sql mysql r reactjs node.js arrays c asp.net json

        Popular Questions

        • How do I undo the most recent local commits in Git?
        • How can I remove a specific item from an array in JavaScript?
        • How do I delete a Git branch locally and remotely?
        • Find all files containing a specific text (string) on Linux?
        • How do I revert a Git repository to a previous commit?
        • How do I create an HTML button that acts like a link?
        • How do I check out a remote Git branch?
        • How do I force "git pull" to overwrite local files?
        • How do I list all files of a directory?
        • How to check whether a string contains a substring in JavaScript?
        • How do I redirect to another webpage?
        • How can I iterate over rows in a Pandas DataFrame?
        • How do I convert a String to an int in Java?
        • Does Python have a string 'contains' substring method?
        • How do I check if a string contains a specific word?

        Copyright © 2021 Jogjafile Inc.

        • Disclaimer
        • Privacy
        • TOS
        • Homegardensmart
        • Pricesm.com
        • Aftereffectstemplates
        • Jogjafile