如何在 Laravel 5 中将第二个变量从 routes.php 传递到控制器


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] 位是发明的,不起作用)

当我打开一个"主记录"时,我想在控制器中使用完全相同的功能(在 RecordController 中显示函数),但我想传递一个额外的参数(类似于"masterrecord = true"),这会对功能进行轻微更改。我知道我可以引用不同的函数,但我真的不想重复相同的代码。

这是我想在RecordController中拥有的东西,但我不确定如何使其工作:

public function show($id, $masterrecord = false)

然后对于records/id路线,我将主记录保留为假,对于masterrecord/id路线,我将能够将第二个标志标记为真。

有什么想法吗?

如果您确实愿意,可以在路由定义中传递硬编码值。然后,您可以从路由的操作数组中提取它。为您提供另一种选择。

Route::get('masterrecord/{id}', [
    'uses' => 'RecordController@show',
    'masterrecord' => true,
]);
public function show(Request $request, $id)
{
    $action = $request->route()->getAction();
    if (isset($action['masterrecord'])) {
        ...
    }
    ...
}

根据需要调整命名。

Asklagbox博客 - Laravel的随机提示和技巧

只需将值设置为可选并由 deafult 设置即可

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);
}