![](/img/trans.png)
[英]How to use controller from vendor in laravel routes.php file?
[英]How to pass a second variable from routes.php to a controller in Laravel 5?
我在定義了以下路線routes.php
中Laravel 5:
Route::get('records/{id}', 'RecordController@show');
但是,我想要一條類似的路線,例如:
Route::get('masterrecord/{id}', 'RecordController@show[masterrecord=true]');
([masterrecord = true]位是發明的,不起作用)
當我打開“ masterrecord”時,我想在控制器中使用完全相同的功能(RecordController中的show函數),但是我想傳遞一個額外的參數(例如“ 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'])) {
...
}
...
}
調整命名方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.