問題描述
我有兩種類型的用戶,我已經創建了多個中間件.
I've two types for user and I've created multiple middlewares.
有些路由需要允許兩種類型的用戶.
Some routes need to allow for both type of user.
我正在嘗試以下代碼:
Route::group(['namespace' => 'Common', 'middleware' => ['Auth1', 'Auth2']], function() {
Route::get('viewdetail', array('as' => 'viewdetail', 'uses' => 'DashboardController@viewdetail'));
});
但它不起作用:(
推薦答案
中間件應該返回響應或將請求傳遞到管道中.中間件彼此獨立,不應該知道其他中間件在運行.
Middleware is supposed to either return a response or pass the request down the pipeline. Middlewares are independent of each other and shouldn't be aware of other middlewares run.
您需要實現一個單獨的中間件,允許 2 個角色或單個中間件,將允許的角色作為參數.
You'll need to implement a separate middleware that allows 2 roles or single middleware that takes allowed roles as parameters.
選項 1:只創建一個中間件是 Auth1 和 Auth2 的組合版本,用于檢查 2 種用戶類型.這是最簡單的選擇,雖然不是很靈活.
Option 1: just create a middleware is a combined version of Auth1 and Auth2 that checks for 2 user types. This is the simplest option, although not really flexible.
選項 2:由于 5.1 版 中間件可以接受參數 - 請在此處查看更多詳細信息:https://laravel.com/docs/5.1/middleware#middleware-parameters.您可以實現一個單一的中間件,該中間件將接受用戶角色列表進行檢查,并在您的路由文件中定義允許的角色.以下代碼應該可以解決問題:
Option 2: since version 5.1 middlewares can take parameters - see more details here: https://laravel.com/docs/5.1/middleware#middleware-parameters. You could implement a single middleware that would take list of user roles to check against and just define the allowed roles in your routes file. The following code should do the trick:
// 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
}
這篇關于如何為路由 laravel 5 使用“OR"中間件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!