如何将第二个变量从 routes.php 传递到 Laravel 5 中的控制器?
How to pass a second variable from routes.php to a controller in Laravel 5?
我在 Laravel 5 中的 routes.php
中定义了以下路由:
Route::get('records/{id}', 'RecordController@show');
但是,我想要一条类似的路线:
Route::get('masterrecord/{id}', 'RecordController@show[masterrecord=true]');
([masterrecord=true] 位是发明的并且不起作用)
当我打开 'masterrecord' 时,我想在控制器中执行完全相同的功能(show RecordController 中的功能),但我想通过一个额外的参数(类似于 'masterrecord = true'),它会使功能发生轻微变化。我知道我可以引用不同的函数,但我真的不想重复相同的代码。
这是我 喜欢 在 RecordController 中拥有的东西,但我不确定如何让它工作:
public function show($id, $masterrecord = false)
然后对于 records/id
路由,我会将 masterrecord 保留为 false,对于 masterrecord/id
路由,我可以将第二个标志标记为 true。
有什么想法吗?
只需将值设为可选并默认设置即可
Route::get('masterrecord/{id}/{masterrecord?}', 'RecordController@show');
控制器:
public function show($id, $masterrecord = false) {
if($masterrecord) // only when passed in
}
您不需要重复任何代码,只需要一个调用 show
方法的主记录方法:
Route::get('records/{id}', 'RecordController@show');
Route::get('masterrecord/{id}', 'RecordController@showMasterRecord');
public function show($id, $master = false) {
if ($master) {
...
}
...
}
public function showMasterRecord($id) {
return $this->show($id, true);
}
如果你真的想要,你可以在路由定义中传递一个硬编码值。然后你可以从路由的动作数组中提取它。给你另一个选择。
Route::get('masterrecord/{id}', [
'uses' => 'RecordController@show',
'masterrecord' => true,
]);
public function show(Request $request, $id)
{
$action = $request->route()->getAction();
if (isset($action['masterrecord'])) {
...
}
...
}
随意调整命名。
我在 Laravel 5 中的 routes.php
中定义了以下路由:
Route::get('records/{id}', 'RecordController@show');
但是,我想要一条类似的路线:
Route::get('masterrecord/{id}', 'RecordController@show[masterrecord=true]');
([masterrecord=true] 位是发明的并且不起作用)
当我打开 'masterrecord' 时,我想在控制器中执行完全相同的功能(show RecordController 中的功能),但我想通过一个额外的参数(类似于 'masterrecord = true'),它会使功能发生轻微变化。我知道我可以引用不同的函数,但我真的不想重复相同的代码。
这是我 喜欢 在 RecordController 中拥有的东西,但我不确定如何让它工作:
public function show($id, $masterrecord = false)
然后对于 records/id
路由,我会将 masterrecord 保留为 false,对于 masterrecord/id
路由,我可以将第二个标志标记为 true。
有什么想法吗?
只需将值设为可选并默认设置即可
Route::get('masterrecord/{id}/{masterrecord?}', 'RecordController@show');
控制器:
public function show($id, $masterrecord = false) {
if($masterrecord) // only when passed in
}
您不需要重复任何代码,只需要一个调用 show
方法的主记录方法:
Route::get('records/{id}', 'RecordController@show');
Route::get('masterrecord/{id}', 'RecordController@showMasterRecord');
public function show($id, $master = false) {
if ($master) {
...
}
...
}
public function showMasterRecord($id) {
return $this->show($id, true);
}
如果你真的想要,你可以在路由定义中传递一个硬编码值。然后你可以从路由的动作数组中提取它。给你另一个选择。
Route::get('masterrecord/{id}', [
'uses' => 'RecordController@show',
'masterrecord' => true,
]);
public function show(Request $request, $id)
{
$action = $request->route()->getAction();
if (isset($action['masterrecord'])) {
...
}
...
}
随意调整命名。