php Laravel:从路由中获取 URL BY NAME
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35752155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Get URL from routes BY NAME
提问by brunomayerc
I'm trying to do something a little different and I couldn't find any way to do it. Maybe my approach is wrong but either way I figured I might find some help here.
我正在尝试做一些不同的事情,但我找不到任何方法来做到这一点。也许我的方法是错误的,但无论如何我想我可能会在这里找到一些帮助。
I have a Laravel 5 project and you know how you can get the current route name by using:
我有一个 Laravel 5 项目,您知道如何使用以下方法获取当前路由名称:
\Request::route()->getName();
So I'm actually looking to do the exact opposite. Maybe not the exact opposite but what I need is to retrieve my route URL based on the name that I gave to that route. Here is my dream scenario.
所以我实际上正在做完全相反的事情。也许不是完全相反,但我需要的是根据我给该路由的名称检索我的路由 URL。这是我梦想中的场景。
my routes.php:
我的路线.php:
Route::any('/hos', "HospitalController@index")->name("hospital");
What I would like to doin my controller that I have no idea how to or even if is possible:
我想在我的控制器中做但我不知道如何做或什至可能做的事情:
// I have no idea if this is possible but thats what I'm trying to accomplish
$my_route_url = \Request::route()->getURLByName("hospital");
echo $my_route_url; // this would echo: "/hos"
I might be using the wrong approach here so maybe you guys can help me out and shine some light on the issue.
我可能在这里使用了错误的方法,所以也许你们可以帮助我解决这个问题。
Thanks!
谢谢!
回答by David Nguyen
$url = route('routeName');
$url = route('routeName');
if there is a param
如果有参数
$url = route('routeName', ['id' => 1]);
$url = route('routeName', ['id' => 1]);
回答by Yusuf Ali
I guess you are trying to rename your route into a specify one In the web.php file
我猜您正试图将您的路线重命名为 web.php 文件中的指定路线
Route::get('anyroute', array('as' => 'newname', function() {
$url = route('new_name');
return "This is the $url";
}));