Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

php - How to use 'OR' middleware for route laravel 5

I've two types for user and I've created multiple middlewares.

Some routes need to allow for both type of user.

I've trying following code:

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

But its not working :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

You'll need to implement a separate middleware that allows 2 roles or single middleware that takes allowed roles as parameters.

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.

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...