2016-09-06 46 views
6

我有兩種類型的用戶,我創建了多箇中間件。如何使用'OR'中間件路由laravel 5

某些路線需要允許這兩種類型的用戶。

我想下面的代碼:

Route::group(['namespace' => 'Common', 'middleware' => ['Auth1', 'Auth2']], function() { 
    Route::get('viewdetail', array('as' => 'viewdetail', 'uses' => '[email protected]')); 
}); 

但它不工作:(

+0

最適合的授權(門和政策) –

回答

7

中間件應該要麼返回響應或向下傳遞的管道請求中間件是相互獨立的。不應該知道其他中間件運行。

您需要實現一個單獨的中間件,讓兩個角色或單一的中間件是需要讓角色的參數。

選項1:只是創建一箇中間件是Auth1和Auth2的組合版本,用於檢查2個用戶類型。這是最簡單的選擇,雖然不是很靈活。

選項2:因爲5.1版中間件可以帶參數 - 在這裏看到更多的細節:https://laravel.com/docs/5.1/middleware#middleware-parameters。您可以實現一箇中間件,該中間件將獲取用戶角色列表以進行檢查,並只在路由文件中定義允許的角色。下面的代碼應該做的伎倆:

// define allowed roles in your routes.php 
Route::group(['namespace' => 'Common', 'middleware' => 'checkUserRoles:role1,role2', function() { 
    //routes that should be allowed for users with role1 OR role2 go here 
}); 

// PHP < 5.6 
// create a parametrized middleware that takes allowed roles as parameters 
public function handle($request, Closure $next) { 

    // will contain ['role1', 'role2'] 
    $allowedRoles = array_slice(func_get_args(), 2); 

    // do whatever role check logic you need 
} 

// PHP >= 5.6 
// create a parametrized middleware that takes allowed roles as parameters 
public function handle($request, Closure $next, ...$roles) { 

    // $roles will contain ['role1', 'role2'] 

    // do whatever role check logic you need 
} 
1

這個例子 How to pass multiple parameters to middleware with OR condition in Laravel 5.2

而不是添加多個參數的處理方法,並具有每次添加一個新的角色添加到您的應用程序進行更新了,你可以使其動態。

中間件

路線

Route::group(['middleware' => ['role_check:default,admin,manager']], function() { 
    Route::get('/user/{user_id}', array('uses' => '[email protected]', 'as' => 'showUserDashboard')); 
}); 

這將檢查被驗證的用戶擁有所提供的角色中的至少一個,如果是,將請求傳遞到下一個中​​間件疊加。當然,hasRole()方法和角色本身將需要由您執行。

可以使用比中間件PHP 5.6

public function handle($request, Closure $next, ...$roles) 
{ 
    foreach ($roles as $role) { 

     try { 
      if ($request->user()->can($role)) { 
       return $next($request); 
     } 

     } catch (ModelNotFoundException $exception) { 
      abort(403); 
     } 
    } 

}