Laravel 5:在 Controller 的构造函数中获取路由参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30815762/
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 5 : get route parameter in Controller 's constructor
提问by BassMHL
I defined routes for a controller this way :
我以这种方式为控制器定义了路由:
/model/{id}/view
/model/something/{id}/edit
I need to get the id parameter in the contructor of this controller. For example :
我需要在这个控制器的构造函数中获取 id 参数。例如 :
class ArtController extends Controller {
public function __construct(Request $request){
//dd($this->route('id')); //Doesn't work
//dd($request->segments()[1]); //this works for the first route but not the second
}
}
How can you get the parameter id
in the constructor of a Controller in Laravel?
如何id
在 Laravel 的 Controller 的构造函数中获取参数?
回答by Rob
You should be able to do something like this
你应该能够做这样的事情
$id = Route::current()->getParameter('id');
Update:
更新:
Starting in laravel 5.4 getParameter
was renamed to parameter
从 laravel 5.4getParameter
开始重命名为parameter
$id = Route::current()->parameter('id');
回答by wbswjc
public function __construct(Request $request)
{
$id = $request->route('id');
dump($id);
}
回答by Heroselohim
You can call anywhere:
您可以在任何地方拨打电话:
request()->route('id');
No need for injection
无需注射
回答by Baku Mn
not use segments use segment
不使用段使用段
public function __construct(Request $request){
dd($request->segment(1));}