Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if current route in Laravel Blade matches a pattern?

I'm checking the routes inside my blade template, to add an active class to a specific li in my menu with this code:

<ul>
    <li class="{{ Request::is('*/sobre') || Request::is('*') ? "active" : "" }}">
        <a href="{{ Route::getCurrentRoute()->parameters()['domain'] . "/sobre" }}">Sobre o salão</a>
    </li>
    <li class="{{ Request::is('*/servicos') ? "active" : "" }}">
        <a href="{{ Route::getCurrentRoute()->parameters()['domain'] . "/servicos" }}">Serviços</a>
    </li>
    <li class="{{ Request::is('*/avaliacoes') ? "active" : "" }}">
        <a href="{{ Route::getCurrentRoute()->parameters()['domain'] . "/avaliacoes" }}">Avaliações</a>
    </li>
    <li class="{{ Request::is('*/galeria') ? "active" : "" }}">
        <a href="{{ Route::getCurrentRoute()->parameters()['domain'] . "/galeria" }}">Fotos</a>
    </li>
</ul>

And those are the routes:

Route::group(['prefix' => '{domain}', 'middleware'=>'salao'], function () {
    Route::get('/', 'Frontend\FrontendSalaoController@sobre');
    Route::get('sobre', 'Frontend\FrontendSalaoController@sobre');
    Route::get('servicos', 'Frontend\FrontendSalaoController@servicos');
    Route::get('avaliacoes', 'Frontend\FrontendSalaoController@avaliacoes');
    Route::get('galeria', 'Frontend\FrontendSalaoController@galeria');
});

When i access the route http://website/x or the route http://website/x/sobre, the active class is positioned correctly. But, if I access the http://website/x/servicos route, the class will be added in the first li and in the servicos li.

How can i handle this?

like image 579
Caio Kawasaki Avatar asked Sep 23 '15 14:09

Caio Kawasaki


People also ask

How to group routes in Laravel?

Creating a basic route group A basic route group in Laravel is created using Route::group() , as shown below. }); The method takes in two parameters, an array, and a callback. The array contains all shared features of the routes in the group.


1 Answers

Request::is('*') actually matches everything so the first item will always have the active class. Instead you should check for '/':

<li class="{{ Request::is('*/sobre') || Request::is('/') ? "active" : "" }}">

The is method even supports multiple parameters, of which only one has to match, so you can shorten it to this:

<li class="{{ Request::is('*/sobre', '/') ? "active" : "" }}">
like image 57
lukasgeiter Avatar answered Sep 28 '22 04:09

lukasgeiter