Skip to content

Instantly share code, notes, and snippets.

@vitorleonel
Last active September 11, 2020 12:59
Show Gist options
  • Save vitorleonel/e4ba465c62b3e03e3170afe397882f79 to your computer and use it in GitHub Desktop.
Save vitorleonel/e4ba465c62b3e03e3170afe397882f79 to your computer and use it in GitHub Desktop.
[Laravel] function to check if it is the current route and return a specific class for make item is active or no
<?php
if (! function_exists('currentRoute'))
{
/**
* Return class when is current route match passed name.
*
* @param string $name
* @param string $htmlClass
* @return string
*/
function currentRoute(string $name, string $htmlClass = 'menu__item--actived') : string
{
return \Illuminate\Support\Facades\Request::routeIs($name) ? $htmlClass : '';
}
}
@vitorleonel
Copy link
Author

Tested on Laravel 7x. In another versions, check exists method "routeIs" on Request class: https://laravel.com/api/7.x/Illuminate/Http/Request.html

@vitorleonel
Copy link
Author

vitorleonel commented Sep 11, 2020

For use custom helpers:

  1. Create Helpers.php in app path. Is a path suggestion.
  2. Copy this code or create own.
  3. In composer.json, add files property within autoload, like:
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "files": [
            "app/Helpers.php"
        ]
    }

@vitorleonel
Copy link
Author

vitorleonel commented Sep 11, 2020

Example of use:

<a class="menu__item {{ currenteRoute('packages*') }}" href="{{ route('packages.pending.view') }}">
    <i class="fas fa-box" data-tippy-content="Meus Pacotes"></i>
</a>

You pass exactly or partial route name. In partial case, use * after or before. That is, any route that starts with packages returns the class activated for my menu item, in my case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment