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”?
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/*’])
Great, didn’t know that! Thanks Peter.
Oh, sorry, I made a mistake, the method doesn’t accept array but multiple arguments. The result is the same, but just to not confuse anybody.
another trick would be
https://github.com/laravel/framework/pull/12748
instead of:
Route::current()->getName() == ‘comp’
you can use:
Route::is(‘comp’)
and of course:
Route::is(‘comp*’)
You can check Route::is(‘route.name.here’) which returns bool either
I’m using segment() function of Request to active high-level menu.
Request::segment(1) === ‘companies’
I just tried @if (request()->route()->getName() == ‘myroutename’) and it worked in laravel 5.4.
How to check if url has a parameter
url like this : http://127.0.0.1:8000/category/create?type=post
is that possible to check
if (Request::is(‘category/*?type=post’)
anyway that’s method not working, any solution for problem like that?
you can check this too for another methods:
https://phpcoder.org/laravel/laravel-get-current-url-blade-page-active-class/
It very helpfully thanks,
Or if (Route::currentRouteName() == ‘comp’) { blabla …}
Helpful, thanks..!
request()->routeIs(‘profile.withdrawal’)
The best way could be request()->route()->named(‘userSettings’)
Povilas Korop, in my opinion, it’s better to include the other ways to check a route from the comments to the article.
This makes the article richer and it takes into account that not everybody would read comments.
Best