" />
      " />
        "/>
        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.1k Views Asked by checker284 At 19 December 2016 at 21:23 2025-12-12T05:22:35.469961

        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

        • proengsoft/laravel-jsvalidation ReferenceError: jQuery is not defined
        • CKFinder Authentication issue with laravel 5
        • Laravel 5: Convert query builder to eloquent
        • Attempting to bind Guzzle Curl Client to Laravel's Service Container -- then Type Hint the Client Fails when attempting to __construct()
        • Composer scripts
        • Can not access the 3rd table in laravel 5 in 3 tables have relationships
        • creating a folder once user registred laravel 5
        • How to use where date(timeline) in Laravel Query Builder
        • SQL weight rows by formula
        • Laravel Eloquent "Many-to-Many-to-One ?"
        • Stopping an infinite loop process in vagrant
        • Insert multiple rows in Laravel
        • Laravel 5 path not writable.Using the Intervention/Image Class
        • Laravel : Saving a belongsToMany relationship
        • Add readonly attribute in form model binding only when editing in laravel 5

        Related Questions in LOCALE

        • Laravel: Locale Session: Controller gets Parameter to change it but it cant. U have to hardcode it
        • Same store information returning in multi-store in observer Magento
        • CentOS 7 Docker Image and locale compilation
        • Java 8 - Locale lookup behavior
        • "Gtk-WARNING **: Locale not supported by C library. Using the fallback 'C' locale." on OS X
        • Get languages my app supports android
        • Get dates from AUT?
        • Change locale in android app (onto Hindi)
        • PHP SoapClient get: ServerCan't find bundle for base name
        • Explain Symfony's "sticky" locale event listener
        • Is it bad that LANG and LC_ALL are empty when running `locale -a` on OS X Yosemite?
        • JSpinner and double with dot or comma as separator
        • Formatting number in European format with two decimals
        • symfony2: how to parameter localization so we can have 2 languages?
        • Symfony2: local changes for same twig view

        Related Questions in MULTILINGUAL

        • SilverStripe - Multilingual Custom Form Template
        • Possibly Multi Language User Error Notification
        • How to Train an Input File containing lines of text in NLTK Python
        • REST: not all representations immediately available
        • Storing Multilingual/unicode characters(thai,hindi,philliphine) in a MYSQL database
        • Localization of Telerik Reports with different Cultures- in MVC application
        • Date Picker with Multilingual support in Asp.net
        • Umbraco 404 with different culture not working
        • Sitecore empty field in multi culture
        • eDismax queries with stopwords and language specific fields
        • Laravel5 multilanguage domains
        • How to model multilingual entities in relational databases
        • Input type=File File Upload Language
        • Format date (with different input) php
        • Form validation ignores language when changed during run-time

        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

        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
        • Math
        • Aftereffectstemplates