wobsoriano
wobsoriano

Reputation: 13452

Laravel get current route

I have some navigation links and I want to get the current route in laravel 5 so that I can use the class active in my navigations. Here are the sample links:

<li class="active"> <a href="/">Home</a> </li>
<li> <a href="/contact">Contact</a> </li>
<li> <a href="/about">About</a> </li>

As you can see, in the Home link there is the active class which means that it is the current selected route. But since I am using laravel blade so that I would not repeat every navigation links in my blades, I can't use the active class because I only have the navigation links in my template.blade.php. How can I possibly get the current route and check if it is equal to the current link? Thank you in advance.

Upvotes: 4

Views: 4809

Answers (4)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41360

Simple way is always better, just use the same function you use to generate links and it will give you all, including the flexibility to use wild cards

<a class="nav-link {{ Request::url() === route("products.list", [$group_key]) ? 'active' : '' }}" 
    href="{{ route("products.list", [$group_key]) }}"
    >
    LInk text
</a>

Plus, you still are going to have only one place to manage URL-s - your router files.

Upvotes: 0

wobsoriano
wobsoriano

Reputation: 13452

So I got it working with some little tricks. For example the url in the address bar is http://localhost:8000/tourism/places.

If I will use the Request::path() method, I will get tourism/places. But what I wanted to get is the tourism part only so what I did is this:

$currentPath = Request::path();

$values = explode("/", $currentPath);

$final = $values[0];

Now the $final variable will have the value "tourism".

Now to make the variable load globally, I included the code in the AppServiceProvider.php inside the public function boot().

public function boot()
{
    $currentPath = Request::path();

    $values = explode("/", $currentPath);

    $final = $values[0];

    view()->share('final', $final);
}

And lastly in my blade template,

<li @if ($final== "tourism") class="active" @endif>
<a href="/tourism/places">Places</a>
</li>

Upvotes: 0

Basit
Basit

Reputation: 971

You can use named routes like

Route::get('/', ['as'=>'home', 'uses'=>'PagesController@index']);

and then in the view you can do the following

 <li {!! (Route::is('home') ? 'class="active"' : '') !!}>
         {!! link_to_route('home', 'Home') !!}
        </li>

Upvotes: 3

Chris
Chris

Reputation: 4810

$uri = Request::path()

Check out the docs

Upvotes: 5

Related Questions