在Laravel v4中,我可以使用…
Route::currentRouteName()
我如何在Laravel v5和Laravel v6中做到这一点?
在Laravel v4中,我可以使用…
Route::currentRouteName()
我如何在Laravel v5和Laravel v6中做到这一点?
当前回答
Laravel 5.2可以使用
$request->route()->getName()
它会给你当前的路由名。
其他回答
查看\Illuminate\Routing\Router.php,您可以通过在控制器方法中注入路由器来使用方法currentRouteNamed()。例如:
use Illuminate\Routing\Router;
public function index(Request $request, Router $router) {
return view($router->currentRouteNamed('foo') ? 'view1' : 'view2');
}
或者使用Route facade:
public function index(Request $request) {
return view(\Route::currentRouteNamed('foo') ? 'view1' : 'view2');
}
你也可以使用is()方法来检查路由是否被命名为任何给定的参数,但要注意这个方法使用preg_match(),我曾经经历过它导致使用虚线路由名的奇怪行为(如'foo.bar.done')。还有preg_match()的性能问题 这是PHP社区的一个大主题。
public function index(Request $request) {
return view(\Route::is('foo', 'bar') ? 'view1' : 'view2');
}
你可以使用这行代码:url()->current()
在刀片文件中:{{url()->current()}}
你可以在模板中使用:
<?php $path = Route::getCurrentRoute()->getPath(); ?>
<?php if (starts_with($path, 'admin/')) echo "active"; ?>
在laravel 7或8使用辅助功能
获取当前路由名
request()->route()->getName()
要检查路由是否是当前最好创建自己的方法为请求类使用宏
在AppServiceProvider中启动方法:
use Illuminate\Support\Facades\Request;
public function boot()
{
Request::macro('isCurrentRoute', function ($routeNames) {
$bool = false;
foreach (is_array($routeNames) ? $routeNames : explode(",",$routeNames) as $name) {
if(request()->routeIs($name)) {
$bool = true;
break;
}
}
return $bool;
});
}
您可以在刀片或控制器中使用此方法
request()->isCurrentRoute('foo') // string route
request()->isCurrentRoute(['bar','foo','xyz.*']) //array routes
request()->isCurrentRoute('blogs,foo,bar,xyz.*') //string route seperated by comma
您可以使用内置laravel路由方法
request()->routeIs('home');
request()->routeIs('blogs.*'); //using wildcard
有很多方法可以做到这一点。你可以输入:
\Illuminate\Support\Facades\Request::route()->getName()
获取路由名称。