How to check current URL or Route

Tutorial last revisioned on August 17, 2022 with Laravel 9
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/web.php file it looks something like this:
Route::get('/companies', function () {
  return view('companies');
})->name('comp');
So how can you check if current route is 'comp'? Relatively easy:
if (\Route::current()->getName() == 'comp') {
  // We are on a correct route!
}
4. Check by routes names If you are using routes by names, you can check if request matches routes name.
if (request()->routeIs('companies.*')) {
  // will match routes which name starts with companies.
}
or
request()->route()->named('profile')
Will match route named profile. So these are four ways to check current URL or route. Would you add any more "tricks"?

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials