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"?
Dont think that works ... at least on Laravel 11.
On laravel 11 it should be: request()->routeIs("schools.show")