简体   繁体   中英

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:

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)

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. 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:

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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