Php – Laravel 5 check if current url matches action

laravellaravel-5phprouting

I am currently generating my application urls using {{action('Namespace\Class@method')}}. How would I check if the current page request maps to that current action Namespace\Class@method?

I would like to do something like:

<a href="{{action('Namespace\Class@method')}}
  @if (currentAction('Namespace\Class@method'))
    class="active"
  @endif
>Some link</a>

How would I achieve this in Laravel 5?

Best Solution

There's no built in method for this, however you can retrieve the current action name with Route::currentRouteAction(). Unfortunately this method will return a fully namespaced class name. So you will get something like:

App\Http\Controllers\FooBarController@method

You can either check for that or use something like ends_with so you don't have to specify the full path:

@if(ends_with(Route::currentRouteAction(), 'FooBarController@method'))

You might also consider naming your routes with 'as' => 'route.name'. This would allow you to use: Route::is('route.name')