获取控制器中的第 n 个路由参数
Getting the nth route parameter in a controller
我在 routes.php 中定义了一条类似于:
的路线
Route::get('something/{firstId}/{secondId}/{thirdId}/{nthId}', 'SomeController@read')->name('read');
在我的控制器中,我这样设置,效果很好:
public function read($firstId, $secondId, $thirdId, $nthId, Request $request){
...
}
对于特定方法,我不需要 $firstId
、$secondId
等。我只需要 $nthId
。是否可以设置我的控制器,以便我可以只获取第 n 个参数并简化我的代码?例如:
public function read($nthId, Request $request){
...
}
您可以使用 variadic 设置参数列表,前面 ...
在 php.net arguments page 上有一个有趣的标题,这是:
因此在你的情况下你会:
public function read(Request $request, ...$ids){
$id2 = $ids[1]; //here is the second path parameter in /id1/id2/id3/..n
...
}
一件事是可变参数必须在声明的最后。
Ps: I might not be totally correct about injecting other parameters but at least with the example above, it worked correctly.
我在 routes.php 中定义了一条类似于:
的路线Route::get('something/{firstId}/{secondId}/{thirdId}/{nthId}', 'SomeController@read')->name('read');
在我的控制器中,我这样设置,效果很好:
public function read($firstId, $secondId, $thirdId, $nthId, Request $request){
...
}
对于特定方法,我不需要 $firstId
、$secondId
等。我只需要 $nthId
。是否可以设置我的控制器,以便我可以只获取第 n 个参数并简化我的代码?例如:
public function read($nthId, Request $request){
...
}
您可以使用 variadic 设置参数列表,前面 ...
在 php.net arguments page 上有一个有趣的标题,这是:
因此在你的情况下你会:
public function read(Request $request, ...$ids){
$id2 = $ids[1]; //here is the second path parameter in /id1/id2/id3/..n
...
}
一件事是可变参数必须在声明的最后。
Ps: I might not be totally correct about injecting other parameters but at least with the example above, it worked correctly.