简体   繁体   English

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

[英]How to pass a second variable from routes.php to a controller in Laravel 5?

I have the following route defined in routes.php in Laravel 5: 我在定义了以下路线routes.php中Laravel 5:

Route::get('records/{id}', 'RecordController@show');

However, I'd like to have a similar route which is something like: 但是,我想要一条类似的路线,例如:

Route::get('masterrecord/{id}', 'RecordController@show[masterrecord=true]');

(The [masterrecord=true] bit is invented and doesn't work) ([masterrecord = true]位是发明的,不起作用)

When I open a 'masterrecord' then I'd like to exact same function in the controller ( show function in RecordController), but I'd like to pass an extra parameter (something like 'masterrecord = true') which would make a slight change in the functionality. 当我打开“ masterrecord”时,我想在控制器中使用完全相同的功能(RecordController中的show函数),但是我想传递一个额外的参数(例如“ masterrecord = true”),功能上的变化。 I known I could refer to a different function but I really don't want to be repeating the same code. 我知道我可以引用一个不同的函数,但是我真的不想重复相同的代码。

Here is the kind of thing I'd like to have in RecordController but I'm not sure how to make it work: 这是什么样的事情,我在RecordController,但我不知道如何使它发挥作用:

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

And then for the records/id routes I would leave masterrecord to be false, and for the masterrecord/id routes I'd be able to mark the second flag as true. 然后对于records/id路由,我将masterrecord保留为false,对于masterrecord/id路由,我将第二个标志标记为true。

Any ideas? 有任何想法吗?

Just make the value optional and set it by deafult 只需将值设为可选,然后默认即可设置

Route::get('masterrecord/{id}/{masterrecord?}', 'RecordController@show');

Controller: 控制器:

public function show($id, $masterrecord = false) {
    if($masterrecord) // only when passed in
}

You don't need to be repeating any code, just have a master-record method that calls the show method: 您无需重复任何代码,只需拥有一个调用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);
}

If you really want to you can pass a hardcoded value in the route definition. 如果确实需要,可以在路由定义中传递一个硬编码的值。 Then you can pull it from the route's action array. 然后,您可以将其从路线的动作数组中拉出。 Gives you another option. 给您另一个选择。

Route::get('masterrecord/{id}', [
    'uses' => 'RecordController@show',
    'masterrecord' => true,
]);

public function show(Request $request, $id)
{
    $action = $request->route()->getAction();

    if (isset($action['masterrecord'])) {
        ...
    }
    ...
}

Adjust naming how ever you want. 调整命名方式。

asklagbox blog - random tips and tricks for laravel asklagbox博客-laravel的随机提示和技巧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM