How to check current URL or Route

Quite often you have a need to check current URL or route and show/hide some element and do some action. Here I will show several ways to do it.

1. Check if URL = X

Simply – you need to check if URL is exactly like X and then you show something.

In Controller:

if (\Request::is('companies')) { 
  // show companies menu or something
}

In Blade file – almost identical:

@if (\Request::is('companies'))  
  Companies menu
@endif

2. Check if URL contains X

A little more complicated example – method Request::is() allows a pattern parameter, like this:

if (\Request::is('companies/*')) { 
  // will match URL /companies/999 or /companies/create
}

3. Check route by its name

As you probably know, every route can be assigned to a name, in routes.php file it looks something like this:

Route::get('/companies', ['as' => 'comp', function () {
  return view('companies');
}]);

So how can you check if current route is ‘comp’? Relatively easy:

if (\Route::current()->getName() == 'comp') {
  // We are on a correct route!
}

So these are three ways to check current URL or route. Would you add any more “tricks”?

Like our articles?
Check out our Laravel online courses!

14 COMMENTS

  1. What I learned only recently was that request method is() accepts also array of patterns, so if I want to highlight high-level navigation for some url I can use

    Request::is([‘companies’, ‘companies/*’])

LEAVE A REPLY

Please enter your comment!
Please enter your name here