在Laravel v4中,我可以使用…
Route::currentRouteName()
我如何在Laravel v5和Laravel v6中做到这一点?
在Laravel v4中,我可以使用…
Route::currentRouteName()
我如何在Laravel v5和Laravel v6中做到这一点?
当前回答
$request->route()->getName();
其他回答
访问当前路由(v5.3起)
你可以在Route虚包上使用current, currentRouteName和currentRouteAction方法来访问处理传入请求的路由信息:
$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();
参考Route虚包和Route实例的底层类的API文档,查看所有可访问的方法。
参考资料:https://laravel.com/docs/5.2/routing#accessing-the-current-route
你可以使用下面的代码在刀片文件中获取路由名称
request()->route()->uri
查看\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');
}
它不需要记忆任何东西,当你想请求某个变量时,通过dd(Request())可以评估哪个变量对你来说是突出的。 在下图中,它很清楚。
如果你想获取路径,显然,这段代码会显示
dd(request()->getpathInfo())
别忘了嵌入 使用说明\ Http \请求; 例如:
if(request()->getpathInfo()=="/logadmin"){
do somethings....
}
你可以在模板中使用:
<?php $path = Route::getCurrentRoute()->getPath(); ?>
<?php if (starts_with($path, 'admin/')) echo "active"; ?>