Last active
September 11, 2020 12:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 : ''; | |
} | |
} |
For use custom helpers:
- Create Helpers.php in app path. Is a path suggestion.
- Copy this code or create own.
- In composer.json, add files property within autoload, like:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/Helpers.php"
]
}
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
Tested on Laravel 7x. In another versions, check exists method "routeIs" on Request class: https://laravel.com/api/7.x/Illuminate/Http/Request.html