Laravel 在类构造函数中检索参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24000823/
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 retrieve param in class constructor
提问by ShiftedReality
Here is my route:
这是我的路线:
Route::controller('/app/{companyId}/', 'HomeController', array('before' => 'auth'));
How can I retrieve $companyId argument in __constructor to avoid retrieving it separate in all my actions?
如何在 __constructor 中检索 $companyId 参数以避免在我的所有操作中单独检索它?
采纳答案by Kirill Fuchs
If you want to get the parameters in the __construct of your controller you could do this:
如果您想在控制器的 __construct 中获取参数,您可以这样做:
class HomeController extends \BaseController
{
public function __construct()
{
$this->routeParamters = Route::current()->parameters();
}
}
it will return a key value list of parameters for the route (ex: ['companyId' => '1']
) @see \Illuminate\Routing\Route
它将返回路由参数的键值列表(例如:['companyId' => '1']
)@ see \Illuminate\Routing\Route
You can also get a specific parameter using the getParameter()or parameter()methods.
您还可以使用getParameter()或parameter()方法获取特定参数。
NOTE:I'm not sure this is such a great idea tho. There might be a more elegant way to solve or better approach to your problem.
注意:我不确定这是个好主意。可能有更优雅的方法来解决您的问题或更好的方法。
回答by arthur.flachs
If you want to make the process simpler, route model binding seems to be the easiest way to go. Instead of having to fetch for the right Model instance in every action of your controller, you pass the right Model to your controller during the routing process.
如果你想让这个过程更简单,路由模型绑定似乎是最简单的方法。不必在控制器的每个操作中获取正确的模型实例,而是在路由过程中将正确的模型传递给控制器。
But you have to use Route::resource. In routes.php :
但是你必须使用 Route::resource。在 routes.php 中:
Route::bind('company', 'Company');
Route::resource('company', 'HomeController');
Then you have an instance of category passed to your controller. For example for /company/1 :
然后你有一个类别的实例传递给你的控制器。例如对于 /company/1 :
public function show($company)
{
// Here you can use, for instance, $company->name
}