2017-05-25 122 views
0

我對這種情況非常困惑。我有兩個資源名稱的路線。路由用戶角色Laravel 5.4

Route::resource('product', 'Product\AreaManagerProductController'); 
Route::resource('product', 'Product\SystemAdminProductController'); 

我需要把它作爲一個,因爲我有一個上下文綁定。

$this->app->when(AreaManagerProductController::class) 
      ->needs(ProductInterface::class) 
      ->give(AreaManagerProductRepository::class); 

      $this->app->when(SystemAdminProductController::class) 
      ->needs(ProductInterface::class) 
      ->give(SystemAdminProductRepository::class); 

上下文綁定工作正常......但我需要改變我的這樣的路線。

Route::resource('product_area_manager', 'Product\AreaManagerProductController'); 
Route::resource('product_system_admin', 'Product\SystemAdminProductController'); 

我創建ProductController和某種奇怪的解決方案。

public function index(){ 

     //Create a conditional statement base on user 

     return app('App\Http\Controllers\Product\AreaManagerProductController')->index(); 

    } 

它可能工作,但它不會觸發中間件......對這種情況最好的做法是什麼? TY

+0

你不應該有你的路線相同的名稱'路線::資源('產品','產品\ AreaManagerProductController');'喜歡的產品。你應該使用不同的路線 –

+0

@NikhilRadadiya說..你不能聲明兩個同名的路線..你可以做的是將控制器擴展到另一個.. Route :: resource('product', 'Product \ AreaManagerProductController');'然後在你的AreaManagerProductController中可以做到,'類AreaManagerProductController擴展SystemAdminProductController' – Demonyowh

+0

我知道它不會與兩個相同的名稱路由資源工作...我會嘗試擴展'ProductController'和看看我能不能做到。謝謝。 – Rbex

回答

3

你可以有你的路線是這樣

Route::group(['prefix' => 'product', 'namespace' => 'Product', 'middleware' => '<your middleware>'], function() { 

     Route::resource('area_manager', 'AreaManagerController'); 
     Route::resource('system_admin', 'SystemAdminController'); 
}); 

我分組的路由,以減少冗餘的原因,我之所以從控制器名稱中刪除產品的,因爲有一個namespace Product已經有不需要長類名。

如果您想訪問AreaManagerControllerSystemAdminController中的某些方法,只需將ProductController擴展到這些控制器即可。

如果您要添加這些控制器內的行動的一些具體middleware,我在route group增加了middleware條款,這將影響到這些控制器,如果沒有必要只是將其刪除。

希望這可以幫助你。

+0

我認爲這是唯一的方法...我最近一直在想它,但我仍然在尋找其他方法。我會接受你的答案,如果我找不到一個...感謝您的幫助。 – Rbex

+0

感謝@Rbex,只是爲了組織和簡單理解我用來寫入這種模式的代碼。 –

+0

是的,如果我們只需要'Route :: resource(Auth :: User() - > roles-> first-> name,Auth :: User() - > roles-> first-> name,那就太棒了。控制器「)'。我試過了...它不起作用。 – Rbex